Laravel 5 Collections: Retrieving and Removing an Element From a Collection With pull

Laravel 5 Collections: Retrieving and Removing an Element From a Collection With pull

Laravel 5

The pull method will remove an item from the collection whilst returning its value. If the item is not in the collection, the optional $default value will be returned. The pull method will modify the original collection.

Signature

public function pull(
    $key,
    $default = null
);

Example Use

The following example demonstrates the basic use of the pull method:

use Illuminate\Support\Collection;

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

// Pull the third value from the collection.
$value = $collection->pull('third');

// null
$doesNotExist = $collection->pull('non-existent');

// default-value
$alsoDoesNotExist = $collection->pull(
                        'non-existent',
                        'default-value'
                    );

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

object(Illuminate\Support\Collection)
  protected 'items' => 
    array
      'first' => string 'I am first'
      'second' => string 'I am second'

Start the Discussion

Leave a comment

Subscribe to our newsletter