PHP array_reduce() Function

PHP array_reduce() function is used to reduce the elements of an array into a single value using a callback function(user-defined function).

Syntax

array_reduce($array, callaback, $initial_parameter)

Parameters

  1. $array(required):  It specifies an input array.
  2. callback(required): It refers to the user-defined function that accepts values from the $array.
  3. $initial_parameter(optional): It is the initial value to pass to the function.

Return value

It returns the reduced result, which can be of any type, such as int, float, or string. (PHP 5.3.0).

If the array is empty and the initial is not passed, this function returns null.

Visual RepresentationVisual Representation of PHP array_reduce() FunctionExample 1: How to Use array_reduce() function

<?php

function f1($x1, $x2)
{
 return $x1 . "_" . $x2;
}

$arr = ["one", "two", "three", "four", "five"];

$result = array_reduce($arr, "f1");

print_r($result);

Output

_one_two_three_four_five

Example 2: Passing the initial parameter in a functionVisual Representation of Passing the initial parameter in a function

<?php

function f1($x1, $x2)
{
 return $x1 + $x2;
}

$arr = [19, 21, 46, 17, 3];

$result = array_reduce($arr, "f1", 7);

print_r($result);

Output

113

In this example, it sums all the values of the array $arr starting from 7, and finally returning the sum of all elements in the array, which is 113.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.