PHP array_reduce() function

Example

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"));
?>

Run Instance

Definition and Usage

The array_reduce() function sends the values in the array to a user-defined function and returns a string.

Comment:If the array is empty and no value is passed initial Parameters, this function returns NULL.

Description

The array_reduce() function iteratively reduces an array to a single value using a callback function.

If the third parameter is specified, it will be treated as the first value in the array, or as the final return value if the array is empty.

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 initial value sent to the function.

Technical Details

Return Value: Return Result Value.
PHP Version: 4.0.5+
Update Log: Since PHP 5.3.0,initial Parameters accept multiple types (mixed), versions prior to PHP 5.3.0 only support integers.

More Examples

Example 1

Set initial Parameters:

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

Run Instance

Example 2

Return Total:

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

Run Instance