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
- $array(required): It specifies an input array.
- callback(required): It refers to the user-defined function that accepts values from the $array.
- $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 RepresentationExample 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 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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.