Описание тега array-reduce

PHP's array_reduce() function allows you to use a callback function to iteratively reduce an array to a single value.

PHP's array_reduce() function allows you to implement a reduce algorithm by using a callback function to iteratively reduce an array to a single value.

As an example, consider this simple code:

function sum($total, $item) {
    return $total + $item;
}

$data = array(1, 2, 3, 4, 5);
$total = array_reduce($data, 'sum', 0);

This will result in calculating a total value of 15, by calling the sum() function 5 times:

  • The first time, it uses the starting value of 0 that we provided, and processes the first item:

    sum(0, 1) // returns 1
    
  • The second time, it uses the return value from the first call, and processes the second item:

    sum(1, 2) // returns 3
    
  • Each time after that, it uses the previous return value, and processes the next item in the array:

    sum(3, 3) // return 6
    sum(6, 4) // returns 10
    sum(10, 5) // returns 15
    
  • And finally, the value returned from the last call is returned back as the result of the array_reduce() function:

    $total = 15;