Laravel array_map array_walk

Array map for collection

        $events = Event::latest()->get();

        $changed = $events->map(function ($value, $key) {
            $value['title'] = strtoupper($value['title']);
            return $value;

array walk for array

 public  function myfunction(&$value, $key)
        $value['title'] = strtoupper($value['title']);            

 public function index( )
        $arr = Event::latest()->get()->toArray();
        // calling array_walk() with no extra parameter
         array_walk($arr, 'self::myfunction');

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 affect 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.

array_filter is really an application of array_walk (or array_reduce) and it more-or-less just provided for convenience.

from Stackoverflow