PHP | array_reduce() Function
This inbuilt function of PHP is used to reduce the elements of an array into a single value that can be of float, integer or string value. The function uses a user defined callback function to reduce the input array.
Syntax:
array_reduce($array, own_function, $initial)
Parameters:
The function takes three arguments and are described below:
- $array (mandatory): This is a mondatory parameter and refers to the original array from which we need to reduce.
- own_function (mandatory): This parameter is als mandatory and refers to the user defined function that is used to hold the value of the $array
- $initial (optional): This parameter is optional and refers to the value to be sent to the function.
Return Value: This function returns the reduced result. It can be of any type int, float or string.
Examples:
Input : $array = (15, 120, 45, 78)
$initial = 25
own_function() takes two parameters and concatenates
them with "and" as a separator in between
Output : 25 and 15 and 120 and 45 and 78
Input : $array = array(2, 4, 5);
$initial = 1
own_function() takes two parameters
and multiplies them.
Output : 40
In this program we will see how an array of integer elements is reduced to a single string value. We also passed the intial element of our choice.
<?php // PHP function to illustrate the use of array_reduce() function own_function($element1, $element2) { return $element1 . " and " . $element2; } $array = array(15, 120, 45, 78); print_r(array_reduce($array, "own_function", "Initial")); ?> |
Output:
Initial and 15 and 120 and 45 and 78
In the below program, the array_reduce reduces the given array to the product of all the elements of the array using the own_function().
<?php // PHP function to illustrate the use of array_reduce() function own_function($element1, $element2) { $element1 = $element1 * $element2; return $element1; } $array = array(2, 4, 5, 10, 100); print_r(array_reduce($array, "own_function", "2")); ?> |
Output:
80000
Reference:
http://php.net/manual/en/function.array-reduce.php
Recommended Posts:
- How to call a function that return another function in JavaScript ?
- How to get the function name from within that function using JavaScript ?
- How to get the function name inside a function in PHP ?
- PHP | Ds\Set contains() Function
- p5.js | nf() Function
- p5.js | arc() Function
- p5.js | nfc() function
- p5.js | min() function
- PHP | dir() Function
- p5.js | second() function
- p5.js | hue() function
- CSS | url() Function
- PHP | Ds\Set first() Function
- p5.js | max() function
- PHP | Ds\Set last() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



