PHP array_reduce()Functions
Examples
Send the values in the array to a user-defined function and return a string:
<?php
function myfunction($v1,$v2)
{
return $v1 . "-" . $v2;
}
$a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction"));
?>
function myfunction($v1,$v2)
{
return $v1 . "-" . $v2;
}
$a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction"));
?>
Run example »
Definition and Usage
The array_reduce() function sends the values in the array to a user-defined function and returns a string.
Note:If the array is empty or the initial value is not passed, this function returns NULL.
Syntax
array_reduce(array,myfunction,initial)
| Parameters | Description |
|---|---|
| array | Required. Specifies the array. |
| myfunction | Required. Specifies the name of the function. |
| initial | Optional. Specifies the first value sent to the function for processing. |
Technical Details
| Return value: | Returns the result value. |
|---|---|
| PHP Version: | 4.0.5+ |
| Changelog: | As of PHP 5.3.0,initialThe parameter accepts multiple types (mixed). Versions before PHP 5.3.0 only supported integers. |
More Examples
Example 1
With the initial parameter:
<?php
function myfunction($v1,$v2)
{
return $v1 . "-" . $v2;
}
$a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction",5));
?>
function myfunction($v1,$v2)
{
return $v1 . "-" . $v2;
}
$a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction",5));
?>
Run example »
Example 2
Return the sum:
<?php
function myfunction($v1,$v2)
{
return $v1+$v2;
}
$a=array(10,15,20);
print_r(array_reduce($a,"myfunction",5));
?>
function myfunction($v1,$v2)
{
return $v1+$v2;
}
$a=array(10,15,20);
print_r(array_reduce($a,"myfunction",5));
?>
Run example »
Complete PHP Array Reference Other Extensions