Laravel Array Helper Function: array_add

November 18, 2016 —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.

The signature for the add helper method is:

add($array, $key, $value)

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($myArray, 'insect', 'Extatosoma Tiaratum');

the end result would be:

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

#array_add($array, $key, $value)

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.