Latest web development tutorials

PHP array_reduce () function

PHP Array Reference Complete PHP Array Reference

Examples

Send values ​​in the array to a user-defined function, and returns a string:

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

Running instance »

Definition and Usage

array_reduce () function to send an array of value to a user-defined function, and returns a string.

NOTE: If the array is empty or the initial value is passed, the function returns NULL.


grammar

array_reduce( array,myfunction,initial )

参数 描述
array 必需。规定数组。
myfunction 必需。规定函数的名称。
initial 可选。规定发送到函数处理的第一个值。

technical details

return value: Return result value.
PHP version: 4.0.5+
Update log: Since PHP 5.3.0 onwards, initial parameter accepts multiple types (mixed), PHP versions prior to 5.3.0 only supports integer.


More examples

Example 1

With initial parameters:

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

Running instance »

Example 2

Returns the sum of:

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

Running instance »


PHP Array Reference Complete PHP Array Reference