Go to the source code of this file.
Enumerations | |
enum | ALGO_MAP_VERSION |
Functions | |
Algo_map () |
|
|
|
Applies a callback(or code) to the elements of given arrays. This function acts much like the perl 'map' keyword, it pass through all array parameters and apply a callback function to each elements of these arrays. See examples below to an overview of Algo_map() usage. *IMPORTANT* Please note that the callback function needs to return something, when you don't want your function to return an element or an hashtable, just return an empty array(). example 1 : Simple use, this example compose an hashtable with an array. <?php function myfunc($a) { return array($a=>1); } $a_pam = array("apple", "pie", "cherry"); $result = Algo_map('myfunc', $a_pam); // $result ==> array("apple"=>1, "pie"=>1, "cherry"=>1); ?> You can pass more than one array as parameters. The number of elements of each array should be at least equal to the number of elements of the first array. If count($a1) > count($a2), elements of $a2 that doesn't exists will be replaced by a false value. example 2 : Using more than one array with Algo_map() <?php function myfunc($a, $b) { return array($a * $b); } $a_nbr = array(1,2,3,4); $b_nbr = array(1,2,4,8,16); $result = Algo_map('myfunc', $a_nbr, $b_nbr); // $result ==> array(1, 4, 12, 32); ?> example 3 : Problem of array size <?php function myfunc($a, $b) { return array($a * $b); } $a_nbr = array(1,2,3,4,16); $b_nbr = array(1,2,4,8); $result = Algo_map('myfunc', $a_nbr, $b_nbr); // $result ==> array(1, 4, 12, 32, 0); // the fifth element is equal to 0 because the fifth element of $b_nbr // doesn't exists and is replaced by false(ie:0) in the callback // function. ?> example 4 : Defining the function code inside the Algo_map() call <?php $a_t = array("a","b","c","d"); $b_t = array("z","b","e","d"); $result = Algo_map( // first element match the function arguments two vars $a and $b // which will be filled with $a_t[x] and $b_t[x] for x=0 to len(a) '$a,$b', // the second parameter is the callback function code // map always return an array (or an hashtable) 'return($a==$b ? $a : array());', $a_t, $b_t ); // $result ==> array("b","d"); ?> example 5 : Object method callback <?php class Foo { function myCallback($a){ return "-$a-"; } }; $foo = new Foo(); $array = array('a','b','c'); $result = Algo_map($foo, 'myCallback', $array); // $result = array('-a-', '-b-', '-c-'); ?>
Definition at line 145 of file Map.php. References $i. |