Search

Laravel Array Helper Function: array_prepend (Easily Add an Item to the Beginning of an Array)

November 20, 2016 —John Koster

prepend($array, $value, $key = null)

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.

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

1<?php
2 
3use Illuminate\Support\Arr;
4 
5// Create an array to work with.
6$array = [
7 'first_name' => 'Jane',
8 'last_name' => 'Doe'
9];
10 
11// Add a new item to the beginning of the array.
12$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:3 [
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:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5// Create an array to work with.
6$array = ['the', 'community'];
7 
8// Add a new item to the beginning of the array.
9$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]

#array_prepend($array, $value, $key = null)

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.