php array_reduce
PHP function array_reduce(array $array, callable $callback, mixed $initial) mixed
-----------------------------------------------------------------------------
Iteratively reduce the array to a single value using a callback function.
Parameters:
array--$array--The input array.
callable--$callback--The callback function. Signature is callback ( mixed $carry , mixed $item ) : mixed
mixed-$carry
The return value of the previous iteration; on the first iteration it holds the value of $initial.
mixed-$item
Holds the current iteration value of the $input
mixed--$initial--[optional] If the optional initial is available, it will be used at the beginning of the process,
or as a final result in case the array is empty.
Returns: the resulting value.
If the array is empty and initial is not passed, array_reduce returns null.
Example use:
============
#1
$numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
function sum( $oldvalue, $newvalue ) {
return $oldvalue + $newvalue;
}
$data = array_reduce( $numbers, 'sum' );
print_r( $data );
/*---------------------------*/
#2
$numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
function sum( $oldvalue, $newvalue ) {
if ( $newvalue % 2 == 0 ) {
return $oldvalue + $newvalue;
}
return $oldvalue;
}
$data = array_reduce( $number, 'sum' );
print_r( $data );