Instance
Sends a value from the array to the user-defined function and returns a string:
<?phpfunction MyFunction ($v 1, $v 2) {return $v 1. "-" . $v 2;} $a =array ("Dog", "Cat", "Horse");p Rint_r (array_reduce ($a, "myfunction")); >
Definition and usage
The Array_reduce () function sends a value from the array to the user-defined function and returns a string.
Note: If the array is empty or the initial value is not passed, the function returns NULL.
Grammar
Array_reduce (array,myfunction,initial)
| Parameters |
Describe |
| Array |
Necessary. Specifies the array. |
| MyFunction |
Necessary. Specifies the name of the function. |
| Initial |
Optional. Specifies the first value to be sent to the function processing. |
technical details
| return value: |
Returns the result value. |
| php version: |
4.0.5+ |
| update log: |
|
More examples
Example 1
With initial parameters:
<?phpfunction MyFunction ($v 1, $v 2) {return $v 1. "-" . $v 2;} $a =array ("Dog", "Cat", "Horse");p Rint_r (array_reduce ($a, "MyFunction", 5)); >
Example 2
return sum:
<?phpfunction MyFunction ($v 1, $v 2) {return $v 1+ $v 2;} $a =array (10,15,20);p Rint_r (array_reduce ($a, "MyFunction", 5));? >
Array_reduce is not only so powerful. Look at the following example. POPs the first element of the array $arr as the initial value, avoiding the $result being empty in min ($result [' min '], $item [' min ']).
Otherwise the final result min is empty.
$arr = Array (' min ' = = 1.5456, ' max ' = 2.28548, ' volume ' = 23.152), array (' min ' = = 1.5457, ' ma X ' = 2.28549, ' volume ' + 23.152), array (' min ' = = 1.5458, ' max ' = 2.28550, ' volume ' = 23.152), a Rray (' 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);
In short, this is more elegant than foreach and defines variables less. Recommended use.