Pass the values of an array to a user-defined function and return a single string.
<?php function myfunction($v1,$v2) { return $v1 . “-“ . $v2; } $a=array(“Dog”,“Cat”,“Horse”); print_r(array_reduce($a,“myfunction”)); ?> |
The array_reduce()
function passes the values of an array to a user-defined function and returns a single result.
Note: If the array is empty and no initial value is provided, the function returns NULL
.
array_reduce(array, myfunction, initial) |
Parameter |
Description |
array |
Required. Defines an array. |
myfunction |
Required. Provides the name of the function. |
initial |
Optional. Defines the initial value to pass to the function |
Return Value: |
Optional. Defines the initial value to pass to the function. |
PHP Version: |
4.0.5+ |
PHP Changelog: |
As of PHP 5.3.0, the initial parameter can accept multiple types (mixed). In versions prior to PHP 5.3.0, it only accepted integers. |
With the initial value parameter:
<?php function myfunction($v1,$v2) { return $v1 . “-“ . $v2; } $a=array(“Dog”,“Cat”,“Horse”); print_r(array_reduce($a,“myfunction”,5)); ?> |
Returning a total sum:
<?php function myfunction($v1,$v2) { return $v1+$v2; } $a=array(10,15,20); print_r(array_reduce($a,“myfunction”,5)); ?> |