PHP Function Reference

PHP array_reduce() Function



The PHP array_reduce() function applies iteratively the myfunction to the elements of the array, so as to reduce the array to a single value.

Syntax

array_reduce(array, myfunction, initial)

Parameters

array Required. Specify the input array.
myfunction Required. Specify the name of the function. This function takes two parameters:
myfunction(carry, item)
  • carry: Holds the return value of the previous iteration. In the case of the first iteration it holds the value of initial.
  • item: Holds the value of the current iteration.
initial Optional. Specify the initial value to send to the function.

Return Value

Returns the resulting value. If the array is empty and initial is not passed, it returns null.

Exceptions

NA.

Example:

The example below shows the usage of array_reduce() function.

<?php
function sum($carry, $item) {
  $carry += $item;
  return $carry;
}

function product($carry, $item) {
  $carry *= $item;
  return $carry;
}

$Arr = array(1, 2, 3, 4, 5);

//using sum function
$result1 = array_reduce($Arr, 'sum');
print_r($result1);

echo "\n";

//using product function
$result2 = array_reduce($Arr, 'product', 1);
print_r($result2);
?>

The output of the above code will be:

15
120

Example:

Consider one example where this function is used with an empty array.

<?php
function sum($carry, $item) {
  $carry += $item;
  return $carry;
}

function product($carry, $item) {
  $carry *= $item;
  return $carry;
}

$Arr = array();

//using sum function
$result1 = array_reduce($Arr, 'sum', 'No data to reduce.');
print_r($result1);

echo "\n";

//using product function
$result2 = array_reduce($Arr, 'product', 'No data to reduce.');
print_r($result2);
?>

The output of the above code will be:

No data to reduce.
No data to reduce.

❮ PHP Array Reference