Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_reduce

Reduces an array to a single value.

Syntax

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

Parameters

ParameterTypeDescription
$arrayarrayThe source array.
$callbackcallableA function that receives the accumulated value and the next element.
$initialmixedOptional. The initial accumulated value.

Return value

mixedThe final value.

Examples

Summing a field:

<?php
 
$orders = [['total' => 100], ['total' => 250]];
 
echo array_reduce($orders, fn ($sum, $order) => $sum + $order['total'], 0);

Output:

350

The longest word:

<?php
 
$words = ['pear', 'banana', 'fig'];
 
echo array_reduce($words, fn ($longest, $word) => strlen($word) > strlen($longest) ? $word : $longest, '');

Output:

banana

Notes

Always pass an initial value: without it an empty array gives null.

See also

  • array_map — Applies a function to every element of an array.
  • array_filter — Keeps the array elements that pass a test.
  • array_sum — Returns the sum of the values in an array.

In the tutorial

  • Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.

Thanks for reading!

Donate to the site — we work hard for you.