Page 165 - Open Soource Technologies 304.indd
P. 165
Unit 7: Multidimensional Arrays
7.4.5 Reducing an Array Notes
A cousin of array_walk( ) , array_reduce( ) , applies a function to each element of the array in
turn, to build a single value:
$result = array_reduce(array, function_name [, default ]);
The function takes two arguments: the running total, and the current value being processed.
It should return the new running total. For instance, to add up the squares of the values of an
array, use:
Example:
function add_up ($running_total, $current_value) {
$running_total += $current_value * $current_value;
return $running_total;
} $numbers = array(2, 3, 5, 7);
$total = array_reduce($numbers, ‘add_up’);
// $total is now 87
The array_reduce( ) line makes these function calls:
add_up(2,3)
add_up(13,5)
add_up(38,7)
The default argument, if provided, is a seed value. For instance, if we change the call to array_
reduce( ) in the previous example to:
$total = array_reduce($numbers, ‘add_up’, 11);
The resulting function calls are:
add_up(11,2)
add_up(13,3)
add_up(16,5)
add_up(21,7)
If the array is empty, array_reduce( ) returns the default value. If no default value is given and
the array is empty, array_reduce( ) returns NULL .
7.4.6 Searching for Values
The in_array( ) function returns true or false , depending on whether the first argument is an
element in the array given as the second argument:
if (in_array(to_find, array [, strict])) { ... }
If the optional third argument is true , the types of to_find and the value in the array must match.
The default is not to check the types.
Here’s a simple example:
LOVELY PROFESSIONAL UNIVERSITY 159