Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
February 18, 2005, 7:30 pm
rate this thread
Hi, I have never used array_walk, and quite frankly, cannot see why I
should use it instead of foreach.
Can someone shed some light on the cases where array_walk is the one
to use, and what php developers where thinking when they coded this
Posted using the http://www.dbforumz.com interface, at author's request
Articles individually checked for conformance to usenet standards
Topic URL: http://www.dbforumz.com/PHP-array_walk-ftopict199368.html
Visit Topic URL to contact author (reg. req'd). Report abuse:
I'm beginning to wonder myself since array_walk() has more limitations
than us the foreach loop construct inasmuch as direct array
manipulation is concerned.
You don't have to reset the pointer before array_walk() whereas in
foreach you would have to before using it to ensure the looping entails
the entire array; that's the only advantage I can think off offhand.
Nope - www.php.net/foreach
"Note: When foreach first starts executing, the internal array pointer is
automatically reset to the first element of the array. This means that you
do not need to call reset() before a foreach loop."
Presumeably the merit of array_walk is in avoiding code duplication where
you might otherwise have to use several identical foreach blocks
array_walk() should be a little faster than using a foreach() loop, as it's
a built-in function. Isn't terribly useful because it needs a reference. I
use array_map() much more often:
// trimming an array
$a = array_map('trim', $a);
// filename-only of results from glob()
$f = array_map('basename', glob("*.gif"));
Note: Also note that foreach operates on a copy of the specified array and
not the array itself. Therefore, the array pointer is not modified as with
the each() construct, and changes to the array element returned are not
reflected in the original array. However, the internal pointer of the
original array is advanced with the processing of the array. Assuming the
foreach loop runs to completion, the array's internal pointer will be at
the end of the array.
So foreach makes a copy, and nested foreach's make more copies. Sometimes
this is very bad.
I mostly use while(list($xKey,$xVal)=each($aArray)) for string indexed
arrays and $iCount=count($aArray) for($i=0;$i<$iCount;$i++) for number
indexed arrays. Can't always just use these though :(
As per Zend PHP certification book :)
A: Because it disrupts the natural flow when reading
Q: Why is it bad to top post?
- » Passing HTTP POST information to another script - How?
- — Previous thread in » PHP Scripting Forum