November 19, 2016 —John Koster
set(&$array, $key, $value)
The set
helper method is the logical opposite of the forget
(discussed in the Laravel Array Helper Function: array_forget article) method. its purpose is to set values within an array.
The set
method also uses dot notation for its $key
value. We will use the set
function to create a simple array:
1<?php2 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');
This function affects the original $array
.
Which would produce a familiar looking array:
1array(1) {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<?php2 3Arr::set($testArray, 'person.first_name', 'John');
The $testArray
would now look like this:
1array(1) {2 ["person"] array(2) {3 ["first_name"] "John"4 ["last_name"] "Doe"5 }6}
set
to Change the Entire ArrayThe 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<?php2 3$testArray = [4 'first' => 'element',5 'second' => 'element'6];
Replacing the $array
with a new array
Given the following array:
1<?php2 3$newArray = [4 'third' => 'element',5 'fourth' => 'element'6];
We can reassign the arrays like so:
1<?php2 3use Illuminate\Support\Arr;4 5Arr::set($testArray, null, $newArray);
The value of $testArray
would now be:
1array(2) {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<?php2 3use Illuminate\Support\Arr;4 5$testArray = Arr::set($testArray, null, null);
Setting the $array
to 100
:
1<?php2 3use Illuminate\Support\Arr;4 5$testArray = Arr::set($testArray, null, 100);
array_set(&$array, $key, $value)
The array_set
function is a shortcut to calling Arr::set
. This function is declared in the global namespace.
∎
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.