Laravel 5: Adding or Setting New Array Element Values With set

April 11, 2018 —John Koster

The set helper method is the logical opposite of the forget method. its purpose is to set values within an array.

Mutable Function

This function affects the original $array.

#Signature

The signature of the set method is:

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

#Example Use

The set method also uses dot notation for its $key value. We will use the set function to create a simple array:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5// Create an empty array to work with.
6$testArray = [];
7 
8Arr::set($testArray, 'person.first_name', 'Jane');
9Arr::set($testArray, 'person.last_name', 'Doe');

Which would produce a familiar looking array:

1array {
2 ["person"] array(2) {
3 ["first_name"] "Jane"
4 ["last_name"] "Doe"
5 }
6}

Overwriting the value of first_name is also easy to accomplish:

1<?php
2 
3Arr::set($testArray, 'person.first_name', 'John');

The $testArray would now look like this:

1array {
2 ["person"] {
3 ["first_name"] "John"
4 ["last_name"] "Doe"
5 }
6}

#Using set to change the entire array

The set function can be used to change the entire value of the array. This is accomplished by passing null as the value for $key. When null is used for the $key, the $value will be assigned to the $array variable. The effects of this can be observed below.

For the following examples, the following array definition will be used:

1$testArray = [
2 'first' => 'element',
3 'second' => 'element'
4];

#Replacing the $array With a New Array

Given the following array:

1$newArray = [
2 'third' => 'element',
3 'fourth' => 'element'
4];

We can reassign the arrays like so:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5Arr::set($testArray, null, $newArray);

The value of $testArray would now be:

1array {
2 ["third"] "element"
3 ["fourth"] "element"
4}

#Replacing the $array With a Completely Different Type

Since the set function will give the $array whatever the $value is when the $key is null, the original type of the variable can be changed completely.

For example, setting the $array to null:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5$testArray = Arr::set($testArray, null, null);

Setting the $array to 100:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5$testArray = Arr::set($testArray, null, 100);

#Global array_set Helper Function

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