Search

Laravel 5: Representing Multi-Dimensional Arrays in Dot Notation With dot

April 11, 2018 —John Koster

The dot helper method will take a multi-dimensional array and return a new associative array where the keys are built from all the nested keys, separated with the . character.

#Signature

The signature of the dot method is:

1public static function dot(
2 $array,vvvvv
3 $prepend = ''
4);

#Example Use

The following example demonstrates the dot method without using the $prepend argument:

1use Illuminate\Support\Arr;
2 
3$myArray = [
4 'user' => [
5 'first_name' => 'John',
6 'last_name' => 'Doe',
7 'career' => [
8 'name' => 'Programmer',
9 'description' => 'Make stuffs.'
10 ]
11 ]
12];
13 
14$myArray = Arr::dot($myArray);

The final array would look like this:

1array {
2 ["user.first_name"] "John"
3 ["user.last_name"] "Doe"
4 ["user.career.name"] "Programmer"
5 ["user.career.description"] "Make stuffs."
6}

The dot method also accepts a value for $prepend which will be added to the beginning of all the newly generated keys. Executing the following:

1$myArray = Arr::dot($myArray, 'prepended_');

Would have produced the following array instead:

1array(4) {
2 ["prepended_user.first_name"] "John"
3 ["prepended_user.last_name"] "Doe"
4 ["prepended_user.career.name"] "Programmer"
5 ["prepended_user.career.description"] "Make stuffs."
6}

#Global array_dot Helper Function

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