PHP array_reduce function

Last Updated: February 14, 2022

array_reduce – go through the array and reduce it to a single value using a callback function

Syntax

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

Supports (PHP 4, PHP 5, PHP 7, PHP 8)

Parameters

Parameter Description
array Required. target array
callback Required. number of keys
initial Optional. Specifies the initial value to send to the function

Return Value

returns the resulting value

Example

<?php
function sum($carry, $item)
{
    $carry += $item;
    return $carry;
}
$input = array(1, 2,3);
print_r(array_reduce($input, "sum"));

?>

Output

6
Test