The array_reduce() function sends the values in an array to a user-defined function, and returns a string.
PHP array_reduce() Function has the following syntax.
array_reduce(array,myfunction,initial)
Parameter | Is Required | Description |
---|---|---|
array | Required. | Specifies an array |
myfunction | Required. | Name of the function |
initial | Optional. | Initial value to send to the function |
<?php
function myfunction($v1,$v2){
return $v1 . "-" . $v2;
}
$a=array("A","B","C");
print_r(array_reduce($a,"myfunction"));
?>
The code above generates the following result.
With the initial parameter:
<?php
function myfunction($v1,$v2){
return $v1 . " vs " . $v2;
}
$a=array("PHP","Java","java2s.com");
print_r(array_reduce($a,"myfunction",5));
?>
The code above generates the following result.
Returning a sum:
<?php
function myfunction($v1,$v2){
return $v1+$v2;
}
$a=array(1,2,6);
print_r(array_reduce($a,"myfunction",5));
?>
The code above generates the following result.