Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Webplaats's avatar

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()?

0 likes
3 replies
design_studio's avatar
Level 31

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

Sinnbeck's avatar

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));
1 like
Webplaats's avatar

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 or to participate in this conversation.