When and why use each() or map() on a collection? When and why use each() or map() on a collection? Because both do kind of the same... I am lost in what is best practice. Can anyone elaborate in when you would use each() and when you use map()?
While both iterates over the collection (and you can achieve the same results in both) there intention are not the same.
Use theeach iteration to loop over the collection and run a callback with each item.
use the map iteration to create a new collection, and use that new collection (maybe somewhere else in the application).
Here is the code for each :)
//each
foreach ($this->items as $key => $item) {
if ($callback($item, $key) === false) {
break;
}
}
return $this;
//map
$keys = array_keys($this->items);
$items = array_map($callback, $this->items, $keys);
return new static(array_combine($keys, $items));
Thank you each ;)
I can indeed use this to state my intention very well in the code, thank you for pointing that out @design_studio .
And thank you for your joke @sinnbeck and clarification!
Please sign in or create an account to participate in this conversation.