Laravel 5: Array Helper Functions

Laravel 5: Array Helper Functions

Laravel 5

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:

use Illuminate\Support\Arr;

$originalArray = [
    'fruit'     => 'orange',
    'vegetable' => 'carrot'
];

$anotherArray = array_add($originalArray, 'vehicle', 'car');

Executing var_dump on $originalArray would produce the following output:

array {
    ["fruit"] "orange"
    ["vegetable"] "carrot"
}

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:

array {
    ["fruit"] "orange"
    ["vegetable"] "carrot"
    ["vehicle"] "car"
}

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:

forms = document.forms;

PHP, using Laravel's helper functions:

use Illuminate\Support\Arr;

// Create a multi-dimensional array, to simulate a document and forms.
$testDocument = [
    'document' => [
        'forms' => [

        ]
    ]
];

// Get the forms.
$forms = Arr::get($testDocument, 'document.forms');

// Traditionally, with vanilla PHP:
$forms = $testDocument['document']['forms'];

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

Start the Discussion

Leave a comment

Subscribe to our newsletter