[Beginner] Traversing arrays in PHP
As for my first PHP article, I've chosen to talk about the first thing you will use, after the echo world script, Arrays, that is.
Arrays are, in my opinion, the best way to handle any structure of data (simple data, anything else will go into Objects).
I will use a simple array, be short on descriptions and be practical. I will not explain how all the instruction works (how many, in what order, etc), for those things I recommend programming books, they will save your life, literally.
Anyway, I like to talk less, and write code more, so here it is :
In all examples I`ll work with a simple array (numeric index, no associative).
$arr = array('a1','b2','c3');
The worst way
The first loop you ever encountered, probably was"for", and looked something like this :
for($i = 0; $i < count($arr);$i++) { echo $arr[$i].'-'; } //will output : a1-b2-c3-
This works, but don't do this ever again, it was created only as bad example
. Mostly because it will count the array elements at each iteration.
The bad way
$count = count($arr);
for($i = 0; $i < $count; $i++) {
echo $i . ' = ' . $arr[$i] . ' - ';
} //will output : 0 = a1 - 1 = b2 - 2 = c3 -
Pre calculate the number of elements is a good practice, but when working with PHP we have something better.
Both methods are good with regular arrays, but what do you do when you need associative, or a faster way ?
The best way *
foreach($arr AS $key=>$element) {
echo "{$key} = {$element} - ";
} //will output : 0 = a1 - 1 = b2 - 2 = c3 -
Foreach is the most common and accepted way to walk trough arrays. Foreach is a PHP construct that works with a copy of the array (clones the array in the servers memory).
* Foreach is the fastest way, but in some cases (when working with big arrays or when you want to dynamically modify the array data or keys) is good to avoid. Sometimes running out of memory is worst then a slow script
. For these cases, see the following methods.
Iterators
The next methods make use of the PHP internal iterators (every array has a pointer to the current array element). I usually use these methods in two cases :
- when I want to conserve memory (if you have problems with big query results, you can directly iterate the results, no need to take them "out" in an array see PDO::fetch() )
- modify the actual array while traversing it
reset($arr);//reset the pointer to first element
while (current($arr) !== false) { //be carefull NOT to have boolean elements
echo key($arr).' = '.current($arr).' - ';
next($arr);//move to next element
} //will output : 0 = a1 - 1 = b2 - 2 = c3 -
Working with current() and next() functions can make wonders with your script, another way is to use each() (here in combination with list() )
reset($arr);
while(list($key,$element) = each($arr)) {
echo "$key = $element - ";
} //will output : 0 = a1 - 1 = b2 - 2 = c3 -
Another advantage of each() over foreach() is that you can modify the array while you are traversing it. In a foreach() loop you will modify the array, but you can't see it, because foreach() works with a separate copy of the array, in memory.
$add_once = true;
reset($arr);
while(list($key,$element) = each($arr)) {
echo "$key = $element - "; //add a new element at the end of the array, only once //because if we do it at every iteration, we will end in a //continous loop, and be one step behind the end all the time.
if ($add_once) {
$arr[] = 'another_element';
$add_once = false;
}
} //will output : 0 = a1 - 1 = b2 - 2 = c3 - 3 = another_element -
Actually you can do this trick when using current() and next() too.
reset($arr);
$remove_once = true;
while(current($arr) !== false) {
echo key($arr).' = '.current($arr).' - ';
if ($remove_once)
{unset($arr[3]);//cheat a bit, 3 instead of count($arr)-3
$remove_once = false;
}
next($arr);} //will output : 0 = a1 - 1 = b2 - 2 = c3 -
Conclusion
There are lots of debates and tests regarding which method to use when traversing an array.
I personally recommend foreach() :
- creates a cleaner code
- you can't do anything wrong
- you don't need anything else (like reset())
- after some results sets it seems is the fastest way
Though I never use foreach when dealing with big arrays, like results sets over 1MB or so, works in development mode, but not afterwards.
Learn, read, code, read more
The most compressive website for benchmarks test I could find was http://phpbench.com/ (read it twice, then store it in your bookmarks
).
If you liked this article, you may want to learn other new (cool) "stuff" when working with arrays in PHP : break continue list() sizeof() count() etc.
PHP has many (really many) functions to work with arrays, USE THEM, don't try to reinvent the wheel : http://php.net/manual/en/ref.array.php
Remember
Always unset() your data after you`re done with it, other (developers) will love you
.
If you liked this article, share it.
Tags :
php, array, function, foreach, for, fast, best practices
By .(JavaScript must be enabled to view this email address) • Tagged #PHP Articles • Written October 28 2011 • So far it has 108 views and 0 Comments • Permalink •
There are no comments for this entry yet.
