November 29, 2016 —John Koster
each(callable $callback)
The each
method accepts a $callback
which will be called on each item in the collection. If the $callback
returns false
, the each
method will break from its iterator and return a reference back to the original Collection
instance. The callback should define both an $item
and a $key
parameter. For most use cases, the each
method is functionally identical to PHP's foreach
construct.
1<?php 2 3use Illuminate\Support\Collection; 4 5// Create a new collection instance. 6$collection = new Collection([ 7 'first', 'second', 'third' 8]); 9 10// firstsecondthird11$collection->each(function($item, $key) {12 echo $item;13});14 15// Break out of the loop early. Will display16// 'first' only.17$collection->each(function($item, $key) {18 if ($item == 'second') {19 return false;20 }21 22 echo $item;23});
The each
method does not explicitly allow the modification of a collection's items, and simply returns a reference to the original collection. However, of the way PHP treats objects as references, it is possible to modify the properties of objects within a collection:
1<?php 2 3use Illuminate\Support\Collection; 4 5class User 6{ 7 8 /** 9 * A hypothetical user's first name.10 *11 * @var string12 */13 public $firstName = '';14 15 /**16 * A hypothetical user's favorite number.17 *18 * @var integer19 */20 public $favoriteNumber = 0;21 22 public function __construct($firstName, $favoriteNumber)23 {24 $this->firstName = $firstName;25 $this->favoriteNumber = $favoriteNumber;26 }27 28}29 30// Create a new collection instance.31$collection = new Collection([32 new User('Jane', 7),33 new User('Sarah', 9),34 new User('Ben', 2)35]);36 37// Change everyone's favorite number to 3.38$collection->each(function($item, $key) {39 $item->favoriteNumber = 3;40});
After the above call to each
, the $collection
variable would contain a value similar to the following output:
1object(Illuminate\Support\Collection)[133] 2 protected 'items' => 3 array (size=3) 4 0 => 5 object(User)[134] 6 public 'firstName' => string 'Jane' (length=4) 7 public 'favoriteNumber' => int 3 8 1 => 9 object(User)[135]10 public 'firstName' => string 'Sarah' (length=5)11 public 'favoriteNumber' => int 312 2 =>13 object(User)[136]14 public 'firstName' => string 'Ben' (length=3)15 public 'favoriteNumber' => int 3
It should also be noted that the each
method affects the original Collection
instance and does not return a modified copy of the original Collection
instance.
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.