Search

Laravel 5 Collections: Removing the First Element of a Collection With shift

April 22, 2018 —John Koster

The shift method is used to remove the first item from the collection and return its value. The shift method modifies the collection instance.

The shift method is similar in behavior to PHP's array_shift function.

#Signature

1public function shift();

#Example Use

The following code example shows how to use the shift method:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'first', 'second', 'third'
6]);
7 
8// first
9$firstValue = $collection->shift();

After the above code has executed, the first item from the collection will have been removed. The final value of the $collection variable would be similar to the following output:

1object(Illuminate\Support\Collection)
2 protected 'items' =>
3 array
4 0 => string 'second'
5 1 => string 'third'

Some absolutely amazing
people

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.