Menu Home

array_reduce

osbo.com | PHP | Functions | array_reduce

Iteratively reduce the array to a single value using a callback function

Syntax

array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] ) : mixed

Parameters

array

The input array.

callback ( mixed $carry , mixed $item ) : mixed

carry

Holds the return value of the previous iteration; in the case of the first iteration it instead holds the value of initial.

item

Holds the value of the current iteration.

initial

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.

Return

Returns the resulting value.

Examples

array callback

<?

function myfunction($carry, $item)
{
    $carry += $item;

    return $carry;
}

$array = array(0, 1, 2, 3, 4);
$callback = "myfunction";

$return = array_reduce($array, $callback);

print_r($return);

?>
10

initial | Null

<?

function myfunction($carry, $item)
{
    $carry += $item;

    return $carry;
}

$array = array(0, 1, 2, 3, 4);
$callback = "myfunction";
$initial = null;

$return = array_reduce($array, $callback, $initial);

print_r($return);

?>
10

initial | Not Null

<?

function myfunction($carry, $item)
{
    $carry += $item;

    return $carry;
}

$array = array(0, 1, 2, 3, 4);
$callback = "myfunction";
$initial = 5;

$return = array_reduce($array, $callback, $initial);

print_r($return);

?>
15

initial | Empty Array

<?

function myfunction($carry, $item)
{
    $carry += $item;

    return $carry;
}

$array = array();
$callback = "myfunction";
$initial = "empty";

$return = array_reduce($array, $callback, $initial);

print_r($return);

?>
empty

PHP