Search

Laravel 5 Collections: Adding an Element to the Beginning of a Collection With prepend

April 22, 2018 —John Koster

The prepend method will add a a given $value to the beginning of the collection. You can also supply an optional $key that will be used as the key for the new $value when adding an item to the beginning of an associative array. The prepend method returns a reference to the original collection instance.

#Signature

1public function prepend(
2 $value,
3 $key = null
4);

#Example Use

The following code example demonstrates the usage of the prepend method:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'XS', 'S', 'M', 'L', 'XL'
6]);
7 
8// Add a new item to the beginning of the collection.
9$collection->prepend('Select a shirt size');

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 array
4 0 => string 'Select a shirt size'
5 1 => string 'XS'
6 2 => string 'S'
7 3 => string 'M'
8 4 => string 'L'
9 5 => string 'XL'

The following examples demonstrate the usage of the prepend method when supplying an argument for the $key parameter:

1// Create a new collection to work with.
2$collection = collect([
3 'name' => 'Holiday Jumper',
4 'color' => 'Red'
5]);
6 
7// Add a new item to the beginning of the collection.
8$collection->prepend('XL', 'size');

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

1Collection {
2 #items: array [
3 "size" => "XL"
4 "name" => "Holiday Jumper"
5 "color" => "Red"
6 ]
7}

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.