Oihana PHP

getKeyValue.php

Table of Contents

Functions

getKeyValue()  : mixed
Retrieves a value from an array or object using a dot-notated key path.

Functions

getKeyValue()

Retrieves a value from an array or object using a dot-notated key path.

getKeyValue(array<string|int, mixed>|object $document, string $key[, mixed $default = null ][, string $separator = '.' ][, bool|null $isArray = null ]) : mixed

This function returns the value associated with a flat or nested key from the given array or object. It supports nested keys using a separator (default: '.'). If the path does not exist or a type mismatch occurs, the $default value is returned.

The structure type can be explicitly specified using $isArray, or it will be inferred automatically.

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

The source structure (array or object).

$key : string

The key or property to retrieve, supports nesting (e.g. 'user.name').

$default : mixed = null

The fallback value if the key does not exist. Default is null.

$separator : string = '.'

Separator used to split nested keys. Default is '.'.

$isArray : bool|null = null

Optional: true for array mode, false for object mode, null for auto-detection.

Tags
throws
InvalidArgumentException

If the structure type is invalid or mismatched.

author

Marc Alcaraz (ekameleon)

since
1.0.0
example

Use a basic array key expression :

$doc = ['name' => 'Alice', 'age' => 30];
echo getKeyValue($doc, 'name'); // 'Alice'

Use a complex array key expression :

$doc = ['user' => ['name' => 'Alice']];
echo getKeyValue($doc, 'user.name'); // 'Alice'

Use with an object :

$doc = (object)['user' => (object)['email' => 'a@b.c']];
echo getKeyValue($doc, 'user.email'); // 'a@b.c'

Use a default value if the key not exist :

$doc = ['meta' => ['a' => 1]];
echo getKeyValue($doc, 'meta.b', 'default'); // 'default'

$doc = (object)['a' => 1];
echo getKeyValue($doc, 'b', 42); // 42
Return values
mixed

The value found, or the default if the key path is not valid or not found.


        
On this page

Search results