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

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

Laravel 5

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

public function push(
    $value
);

Example Use

The following code example demonstrates how to use the push method to add an item on the end of a collection:

use Illuminate\Support\Collection;

// Create a new collection instance.
$collection = new Collection([
    'I am first',
    'I am second'
]);

// Push an item onto the collection.
$collection->push('I am third');

After the above code has executed, the $collection variable would contain a value similar to the following output:

object(Illuminate\Support\Collection)
  protected 'items' => 
    array
      0 => string 'I am first'
      1 => string 'I am second'
      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.

Start the Discussion

Leave a comment

Subscribe to our newsletter