Forum Moderators: coopster

Message Too Old, No Replies

want to apply ANY function to every element of an array

user or native functions

         

pixeltierra

7:50 pm on Nov 10, 2006 (gmt 0)

10+ Year Member



we all know that array_walk is great for running an array elements through a user function. But what if I want to addslashes() (or print, or print_r or trim) to every member of an array? Do I have to loop through it manually?

I wrote this function thinking I'd bypass this, but it (surprisingly) only worked with user functions and halted execution on native php functions!

function walk_it (&$array, $func){
foreach($array as $key => $val){
$func($array[$key]);
}
}

Everytime I code I need to process arrays. How could I accomplish something as basic as this (without looping manually)?:

* array_walk($array, 'addslashes');
* array_walk($array, 'print');

eelixduppy

8:02 pm on Nov 10, 2006 (gmt 0)



You can also use array_map [us2.php.net] however, as you may have guessed, it's not going to work for everything. In which case you are going to have to loop through the array and do what needs to be done.

pixeltierra

9:04 pm on Nov 10, 2006 (gmt 0)

10+ Year Member



eelixduppy: thanks for all your help

Array_map is perfect! Except you're right, it doesn't seem to work on everything. Do you happen to know which type of functions it doesn't work on?

eelixduppy

4:03 am on Nov 13, 2006 (gmt 0)



Maybe this [us2.php.net] will answer your question. I don't think the limitations will effect you, though.