Forum Moderators: coopster

Message Too Old, No Replies

Performing a Function on Each Element of an Array

Is array_walk() the way to go?

         

Nick_W

8:06 pm on Apr 16, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi all,

I have (PHP) an multi-dimensional array of values pulled from a database.

If I want to stripslashes() from each element of the array, is array_walk() the way forward, or is there a better way...?

Many thanks...

Nick

DrDoc

8:54 pm on Apr 16, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hello Nick.

From the PHP documentation on array_walk() [php.net]

array_walk -- Apply a user function to every member of an array

Seems like that would be the way to go :)

Of course, there are other ways too. If you want to iterate through the array until you find a match, well, then it's better to use a function where you have more control over the process (such as while() [php.net] or for() [php.net])

foreach() [php.net] is also a possible solution.

andreasfriedrich

11:41 pm on Apr 16, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Note however, that array_walk [php.net] will not walk through your multidimensional array recursively.


function mycb(&$item, $key) {
$item = "->".$item;
}
#
$t['aaron'] = array('carter', 15);
$t['jesse'] = array('mccartney', 16);
#
array_walk [php.net]($t, 'mycb');
#
echo [php.net] "<pre>", print_r [php.net]($t), "</pre>";

will print


Array
(
[aaron] => ->Array
[jesse] => ->Array
)

To get the expected behaviour you need to check whether $item is_array [php.net] is true and call array_walk [php.net] for that array as well. So your callback function would need to look like this:


function mycb(&$item, $key) {
echo [php.net] $item;
if(is_array [php.net]($item)) {
array_walk [php.net]($item, 'mycb');
return;
}
$item = "->".$item;
}

Andreas