184 of 410 menu

The array_reduce Function

The array_reduce function reduces an array to a single value using a callback.

The first parameter is the array, the second is the callback that will be applied sequentially to each element of the array.

The third optional parameter is the initial value from which the array reduction will start. By default, this parameter has the value null.

The callback function receives two parameters. The first value contains the result from the previous iteration. On the first iteration, it contains the value of the third parameter.

The second value of the callback contains the current array element.

The callback will be applied to each array element in turn. The value returned by the callback on the current iteration will become the first parameter of the callback on the next iteration.

Thus, the callback will sequentially apply to each element of the array in turn and eventually produce a value. This value will be the result of the array_reduce function.

Syntax

array_reduce(array $array, callable $callback, mixed $initial = null): mixed

Example

Let's find the sum of the array elements:

<?php $arr = [1, 2, 3, 4, 5]; function func($prev, $elem) { return $prev + $elem; } $res = array_reduce($arr, 'func', 0); echo $res; ?>

Code execution result:

15

See Also

  • the array_map function,
    which applies a function to the elements of an array
  • the array_walk function,
    which calls a function for array elements
  • the array_filter function,
    which filters an array
  • the array_walk_recursive function,
    which recursively calls a function for array elements
byenru