What is the difference between array_map, array_walk, array_filter, array_reduce in PHP?

array_walk() Applies the user-defined callback function to each element of the array array. Returns a boolean. May or May not Modify the original array. To modify original array callback function can accept an argument by reference.

array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map(). So array_map does not modify the original array.

array_filter() Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.
Returns subset of array.

array_reduce() applies iteratively the callback function to the elements of the array, so as to reduce the array to a single value. Returns single value.

The idea of mapping an function to array of data comes from functional programming. You shouldn’t think about array_map as a foreach loop that calls a function on each element of the array (even though that’s how it’s implemented). It should be thought of as applying the function to each element in the array independently.

In theory such things as function mapping can be done in parallel since the function being applied to the data should ONLY effect the data and NOT the global state. This is because an array_map could choose any order in which to apply the function to the items in (even though in PHP it doesn’t).

array_walk on the other hand it the exact opposite approach to handling arrays of data. Instead of handling each item separately, it uses a state (&$userdata) and can edit the item in place (much like a foreach loop). Since each time an item has the $funcname applied to it, it could change the global state of the program and therefor requires a single correct way of processing the items.

Back in PHP land, array_map and array_walk are almost identical except array_walk gives you more control over the iteration of data and is normally used to “change” the data in-place vs returning a new “changed” array.