PHP uses foreach to express array_ walk/array_ filter/array_ map/array_ reduce

Time:2022-1-11

array_ Map (callback, array) I call it array update, which means that a new array is returned after callback operation on each item of the array
array_ Walk (array, callback) I call it data traversal, which means that each item of the array is callback processed without return
array_ Reduce (array, callback) is called data accounting, which means that each item of the array is callback processed, merged and returned as a value
array_ Filter (array, callback) is called array filtering, which means that each item of the array is callback processed, and the value of return true remains in the original array
array_walk/array_filter/array_map/array_reduce
Traversal array, callback function, traversal once, callback once
array_ Walk is equivalent to foreach

$arr = ['client'=>'js','cerver'=>'go'];
array_walk($arr,'walk' );

function walk($v, $k) {
    Echo "key: $k value: $V \ n";
}

For example, remove the front and back whitespace of the array $arr element

array_walk($arr, function(&$v) { $v = trim($v); });
foreach($arr as &$v) { $v = trim($v); }

array_ Filter uses the callback function to filter the cells in the array and returns the filtered array

var_export(
    array_filter([1, 2, 3,4], function($v) {
        return $v > 1;
    })
);

and

foreach([1, 2, 3,4] as $k => $v) {
    if($v > 1) {
        $tmp[$k] = $v;
    }
}
var_export($tmp);

All outputs:

array (
  1 => 2,
  2 => 3,
  3 => 4,
)

PHP array mapping reduction (MapReduce)
array_map/array_reduce
array_ Map: apply the callback function to the cells of the given array

var_export(
    array_map(function ($v) {
        return $v * $v;
    }, [1, 2, 3,4])
);

and

foreach([1, 2, 3,4] as $v) {
    $tmp[] = $v * $v;
}

var_export($tmp);
All outputs:
array (
0 => 1,
1 => 4,
2 => 9,
3 => 16,
)

array_ Reduce iteratively reduces the array to a single value with a callback function

Array can be used for the accumulation of array values_ Reduce function

//Output 16, i.e. 10 + 1 + 2 + 3, where 10 is the initial value
//Output 10, i.e. 0 + 1 + 2 + 3, where 0 is the initial value
echo array_reduce([1, 2, 3], function($result, $item) {
    $result = $result + $item;
    return $result;
}, 0);

Expressed in foreach

$result = 10;
foreach([1, 2, 3] as $v) {
    $result = $result + $v;
}
echo $result;

This work adoptsCC agreement, reprint must indicate the author and the link to this article