Search

Laravel 5: Adding a New Element to the Beginning of an Array With prepend

April 11, 2018 —John Koster

The prepend helper method is used to push a new $value onto the beginning of an existing $array. It defines one optional parameter: $key. If an argument is supplied for $key, the new item will be given that key. Supply a value for $key if you want to control the new items key when adding a new item to an associative array. This method does not affect the original array, and returns a new, modified, copy of the original array.

#Signature

The signature of the prepend method is:

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

#Example Use

The following examples demonstrate the usage of the prepend helper method:

1use Illuminate\Support\Arr;
2 
3// Create an array to work with.
4$array = [
5 'first_name' => 'Jane',
6 'last_name' => 'Doe'
7];
8 
9// Add a new item to the beginning of the array.
10$array = Arr::prepend($array, 26, 'id');

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

1array [
2 "id" => 26
3 "first_name" => "Jane"
4 "last_name" => "Doe"
5]

The following example shows the usage of the prepend method without supplying an argument for the $key parameter:

1use Illuminate\Support\Arr;
2 
3// Create an array to work with.
4$array = ['the', 'community'];
5 
6// Add a new item to the beginning of the array.
7$array = Arr::prepend($array, 'for');

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

1array:3 [
2 0 => "for"
3 1 => "the"
4 2 => "community"
5]

#Global array_prepend Helper Function

The array_prepend helper function is a shortcut to calling the Arr::prepend helper method. This function is declared in the global namespace.

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.