PHP array_reduce () application

array_reduce ($ array, $ callback ($ carry, $ item), $ initial) callback function is calculated by an iterative array element, and returns the final result. $ Carry carrying value of the previous iteration, if this is the first iteration, then this value is $ initial. If a value of $ Initial specified, this parameter is started before processing, or after processing, the processed array is empty, this value is returned.

<?php

function func1($x,$y){
    $y += $x;
    return $y;
}
$arr1 = array(1,2,3,4,5,6);
$return1 = array_reduce($arr1,"func1");
echo $return1;

Results: 21

function func2($x,$y){
    echo $x.' == '.$y."<br>";
    $y *= $x;
    return $y;
}
$arr2 = array(1,2,3,4);
$return2 = array_reduce($arr2,"func2");
echo $return2;

Output process:

== 1
0 == 2
0 == 3
0 4 ==
end result: 0


$return2 = array_reduce($arr2,"func2",1);
echo $return2;

Output process:

1 == 1
1 == 2
2 == 3
6 == 4

The end result: 24

 

$return3 = array_reduce(array(),"func1",'no data');
echo $return3;

Output: 'no data'

Guess you like

Origin blog.csdn.net/uvyoaa/article/details/83472981