Oihana PHP

get.php

Table of Contents

Functions

get()  : mixed
Retrieves a value from an associative array using a key path.

Functions

get()

Retrieves a value from an associative array using a key path.

get(array<string|int, mixed> $array, string|null $key[, mixed $default = null ][, string $separator = '.' ]) : mixed

This function allows navigation through a nested array using a key composed of segments separated by a specified separator (default is a dot). If the key is not found, the function returns a default value.

Parameters
$array : array<string|int, mixed>

The associative array to search within.

$key : string|null

The key path as a string. Can be null, in which case the function returns the entire array.

$default : mixed = null

The default value to return if the key is not found. Defaults to null.

$separator : string = '.'

The separator used to split the key into segments. Defaults to a dot ('.').

Tags
example
$data =
[
    'user' =>
    [
        'name'    => 'Alice',
        'address' =>
        [
            'city' => 'Paris',
            'geo' => [ 'lat' => 48.8566, 'lng' => 2.3522 ],
        ],
    ],
];

echo get($data, 'user.name');             // Alice
echo get($data, 'user.address.city');     // Paris
echo get($data, 'user.address.geo.lat');  // 48.8566
echo get($data, 'user.phone', 'unknown'); // unknown
echo get($data, null);                    // returns entire $data array
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
mixed

The value found in the array or the default value if the key does not exist.


        
On this page

Search results