PHP array_reduce() ফাংশন

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 parameter is passed initial Parameter, this function returns NULL.

Description

The array_reduce() function iterates over the array with a callback function to simplify it to a single value.

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)
Parameter Description
array Required. Specify the array.
myfunction Required. Specify the name of the function.
initial Optional. Specify 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 before 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