What exactly is the difference between array_map
, array_walk
and array_filter
. What I could see from documentation is that you could pass a callback function to perform an action on the supplied array. But I don't seem to find any particular difference between them.
Do they perform the same thing?
Can they be used interchangeably?
I would appreciate your help with illustrative example if they are different at all.
array_map
cannot change the values inside input array(s) whilearray_walk
can; in particular,array_map
never changes its arguments.array_map
cannot operate with the array keys,array_walk
can.array_map
returns a new array,array_walk
only returnstrue
. Hence, if you don't want to create an array as a result of traversing one array, you should usearray_walk
.array_map
also can receive an arbitrary number of arrays and it can iterate over them in parallel, whilearray_walk
operates only on one.array_walk
can receive an extra arbitrary parameter to pass to the callback. This mostly irrelevant since PHP 5.3 (when anonymous functions were introduced).array_map
has the same length as that of the largest input array;array_walk
does not return an array but at the same time it cannot alter the number of elements of original array;array_filter
picks only a subset of the elements of the array according to a filtering function. It does preserve the keys.Example:
Result: