Array_walk equivalent to foreach:
$arr = ['Client'=>'jQuery','Server'=>'PHP'];array_walk($arr, function($v, $k) { echo "键:$k 值:$v\n";});
For example, remove the front and back blanks of the array $arr elements:
array_walk($arr, function(&$v) { $v = trim($v); });foreach($arr as &$v) { $v = trim($v); }array_filter: 用回调函数过滤数组中的单元,返回过滤后的数组var_export( array_filter([1, 2, 3], function($v) { return $v > 1; }));和foreach([1, 2, 3] as $k => $v) { if($v > 1) { $tmp[$k] = $v; }}var_export($tmp);都输出:array ( 1 => 2, 2 => 3,)
PHP Array Map Simplification (MapReduce):
array_map/array_reducearray_map: 将回调函数作用到给定数组的单元上var_export( array_map(function ($v) { return $v * $v; }, [1, 2, 3]));和foreach([1, 2, 3] as $v) { $tmp[] = $v * $v;}var_export($tmp);都输出:array ( 0 => 1, 1 => 4, 2 => 9,)
Array_reduce: Iterating over the array simplification (reduce) to a single value using a callback function
Output 16, which is 10+1+2+3, where 10 is the initial value.
echo array_reduce([1, 2, 3], function($result, $item) { $result = $result + $item; return $result;}, 10);用foreach表达:$result = 10;foreach([1, 2, 3] as $v) { $result = $result + $v;}echo $result;
The effect is the same, but the specific use of the function or foreach faster AH
Reply content:
Array_walk equivalent to foreach:
$arr = ['Client'=>'jQuery','Server'=>'PHP'];array_walk($arr, function($v, $k) { echo "键:$k 值:$v\n";});
For example, remove the front and back blanks of the array $arr elements:
array_walk($arr, function(&$v) { $v = trim($v); });foreach($arr as &$v) { $v = trim($v); }array_filter: 用回调函数过滤数组中的单元,返回过滤后的数组var_export( array_filter([1, 2, 3], function($v) { return $v > 1; }));和foreach([1, 2, 3] as $k => $v) { if($v > 1) { $tmp[$k] = $v; }}var_export($tmp);都输出:array ( 1 => 2, 2 => 3,)
PHP Array Map Simplification (MapReduce):
array_map/array_reducearray_map: 将回调函数作用到给定数组的单元上var_export( array_map(function ($v) { return $v * $v; }, [1, 2, 3]));和foreach([1, 2, 3] as $v) { $tmp[] = $v * $v;}var_export($tmp);都输出:array ( 0 => 1, 1 => 4, 2 => 9,)
Array_reduce: Iterating over the array simplification (reduce) to a single value using a callback function
Output 16, which is 10+1+2+3, where 10 is the initial value.
echo array_reduce([1, 2, 3], function($result, $item) { $result = $result + $item; return $result;}, 10);用foreach表达:$result = 10;foreach([1, 2, 3] as $v) { $result = $result + $v;}echo $result;
The effect is the same, but the specific use of the function or foreach faster AH