Laravel 5 Collections: Adding an Element to the End of a Collection With push

The push
method is the logical opposite of the prepend
method and will push an item onto the end of the collection. The push
method returns a reference to the original collection instance.
The push
method modifies the collection instance it was invoked on.
Signature
1public function push(2 $value3);
Example Use
The following code example demonstrates how to use the push
method to add an item on the end of a collection:
1use Illuminate\Support\Collection; 2 3// Create a new collection instance. 4$collection = new Collection([ 5 'I am first', 6 'I am second' 7]); 8 9// Push an item onto the collection.10$collection->push('I am third');
After the above code has executed, the $collection
variable would contain a value similar to the following output:
1object(Illuminate\Support\Collection)2 protected 'items' =>3 array4 0 => string 'I am first'5 1 => string 'I am second'6 2 => string 'I am third'
It should be noted that the push
method cannot be used to set the key of the item that is being added to the collection.
∎
Thanks for taking the time to read this post! If you found this article useful and want to help support more work like this, please consider sponsoring my work on GitHub, or by checking out some merch.
Sponsor on GitHub Shop Merch