PHP array_reduce() function

PHP array_rand() function
PHP array_replace() function

The array_reduce function sends each value of the given array to the user-defined function and returns a string.

If no initial is passed and the array is empty, the array_reduce function will return NULL.

What is the syntax of the array_reduce function in PHP?

array_reduce(array, myfunction, initial)
ParameterDescription
arraySpecify the array to use – Required
my_functionuser-defined function for array_reduce function – Required
initialSet the initial value to send to the user-defined function – Optional
array_reduce function in PHP

Examples of array_reduce function in PHP

<?php
function myfunction($v1,$v2)
{
return $v1 . "-" . $v2;
}
$a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction"));
?>

In the above example, we use array in array_reduce function which returns the string using a user-defined function.

<?php
function myfunction($v1,$v2)
{
return $v1 . "-" . $v2;
}
$a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction",5));
?>

In the above function, we demonstrate the use of the initial parameter.

<?php
function myfunction($value1,$value2)
{
return $value1+$value2;
}
$a=array(10,15,20);
print_r(array_reduce($arr,"myfunction",5));
?>

I the above example, we calculate the sum of the values and return it. It is also working fine.

PHP array_rand() function
PHP array_replace() function
en English
X
Scroll to Top