array_reduce ($array, own_function, $initial)Parameters:
Function takes three arguments and is described below:
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: 40In this program we will see how an array of integer elements is reduced to a single string value. We also passed the first element of our selection.
// 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 program below, array_reduce reduces the given array to the product of all array elements using own_function().
// 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 Link :
http://php.net/ manual / en / function.array-reduce.php