Laravel 5: Adding Elements to the Array with add

April 11, 2018 —John Koster

The add helper method adds the given $key and $value to an $array if the $key doesn't already exist within the given $array.

#Signature

The signature of the add method is:

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

#Example Use

Consider the following code snippet:

1use Illuminate\Support\Arr;
2 
3$myArray = [
4 'animal' => 'Araripe Manakin',
5 'plant' => 'Pineland Wild Petunia'
6];
7 
8$myArray = Arr::add(
9 $myArray,
10 'insect',
11 'Extatosoma Tiaratum'
12 );

the end result would be:

1array {
2 ["animal"] "Araripe Manakin"
3 ["plant"] "Pineland Wild Petunia"
4 ["insect"] "Extatosoma Tiaratum"
5}

#Global array_add Helper Function

The array_add function is a shortcut to calling Arr::add. 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.