Search

Laravel 5: Array Helper Functions

April 11, 2018 —John Koster

Laravel provides many helper functions for interacting and manipulating array data structures. Laravel's array functions offer additional functionality on top of PHP's built in array functions. The helper functions in this section are located within the "Illuminate\Support\Arr" static class. There are methods defined in the static class that have counterparts defined in the global namespace. These functions appear below each static array method.

#Immutable Arrays

All of the array helper functions below, unless stated otherwise, treat arrays as an immutable data structure. This means that any changes made to an array are returned as a copy of the original array, with the original array remaining unchanged.

Here is a quick example:

1use Illuminate\Support\Arr;
2 
3$originalArray = [
4 'fruit' => 'orange',
5 'vegetable' => 'carrot'
6];
7 
8$anotherArray = array_add($originalArray, 'vehicle', 'car');

Executing var_dump on $originalArray would produce the following output:

1array {
2 ["fruit"] "orange"
3 ["vegetable"] "carrot"
4}

This is because Laravel's functions do not affect the original array (unless stated otherwise).

Running var_dump on $anotherArray, however, would produce the expected results:

1array {
2 ["fruit"] "orange"
3 ["vegetable"] "carrot"
4 ["vehicle"] "car"
5}

#Array Dot Notation

In addition to treating arrays as immutable, Laravel's functions support "dot" notation when accessing items in an array. This is similar to JavaScript's dot notation when accessing object properties.

JavaScript:

1forms = document.forms;

PHP, using Laravel's helper functions:

1use Illuminate\Support\Arr;
2 
3// Create a multi-dimensional array, to simulate a document and forms.
4$testDocument = [
5 'document' => [
6 'forms' => [
7 
8 ]
9 ]
10];
11 
12// Get the forms.
13$forms = Arr::get($testDocument, 'document.forms');
14 
15// Traditionally, with vanilla PHP:
16$forms = $testDocument['document']['forms'];

Using dot notation with Laravel's functions will be explored in more detail in the following articles.

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.