PHP array_reduce() Function
Definition
The array_reduce() function sends the values in an array to a user-defined function, and returns a string.
Syntax
PHP array_reduce() Function has the following syntax.
array_reduce(array,myfunction,initial)
Parameter
Parameter | Is Required | Description |
---|---|---|
array | Required. | Specifies an array |
myfunction | Required. | Name of the function |
initial | Optional. | Initial value to send to the function |
Example
<?php//from w ww . j a v a2s. c o m
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.
Example 2
With the initial parameter:
<?php/*from w ww . java2 s . c o m*/
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.
Example 3
Returning a sum:
<?php/*from ww w . ja v a 2 s. c o m*/
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.