Example
Send the values in the array to the userCustom function, and return a string:
<?php function myfunction($v1,$v2) { return $v1 . "-" . $v2; } $a=array("Dog","Cat","Horse"); print_r(array_reduce($a,"myfunction")); ?>
Definition and usage
array_reduce () function sends the values in the array to the 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 an 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: | Return the result value. |
PHP Version: | 4.0.5+ |
Change Log: | Since PHP 5.3.0, the initial parameter accepts multiple types (mixed), and versions before PHP 5.3.0 only support integers. |
更多实例
实例 1
带 initial 参数:
<?php function myfunction($v1,$v2) { return $v1 . "-" . $v2; } $a=array("Dog","Cat","Horse"); print_r(array_reduce($a,"myfunction",5)); ?>
实例 2
返回总和:
<?php function myfunction($v1,$v2) { return $v1+$v2; } $a=array(10,15,20); print_r(array_reduce($a,"myfunction",5)); ?>
array_reduce的强大不仅如此。看下面的例子。将数组$arr的首个元素弹出,作为初始值,避免min($result['min'], $item['min'])中$result为空。
否则最终结果min是空的。
$arr = array( array('min' => 1.5456, 'max' => 2.28548, 'volume' => 23.152), array('min' => 1.5457, 'max' => 2.28549, 'volume' => 23.152), array('min' => 1.5458, 'max' => 2.28550, 'volume' => 23.152), array('min' => 1.5459, 'max' => 2.28551, 'volume' => 23.152), array('min' => 1.5460, 'max' => 2.28552, 'volume' => 23.152), ); $initial = array_shift($arr); $t = array_reduce($arr, function($result, $item) { $result['min'] = min($result['min'], $item['min']); $result['max'] = max($result['max'], $item['max']); $result['volume'] += $item['volume']; return $result; }, $initial);
总之,这种写法比foreach更优雅,更少的定义变量。推荐使用。
The above is the detailed content of PHP sends the values in the array to the user-defined function and returns a string function array_reduce(). For more information, please follow other related articles on the PHP Chinese website!