Search

Laravel Array Helper Function: array_dot

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

The signature for the dot helper method is:

dot($array, $prepend = '')

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

The final array would look like this:

1array(4) {
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}

#array_dot($array, $prepend = '')

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.