Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

array_reduce

Description

The array_reduce of Array for PHP 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

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

1 · array callback

<?

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

    return $carry;
}

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

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

print_r($return);

?>
6

2 · initial · Null

<?

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

    return $carry;
}

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

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

print_r($return);

?>
6

3 · initial · Not Null

<?

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

    return $carry;
}

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

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

print_r($return);

?>
10

4 · array Empty · initial Null

<?

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

    return $carry;
}

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

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

var_export($return);

?>
NULL

5 · array Empty · initial Not Null

<?

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

    return $carry;
}

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

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

print_r($return);

?>
array is empty
HomeMenu