Oihana PHP

accessors

Table of Contents

Functions

assertDocumentKeyValid()  : bool
Validates the key, separator, and type of the provided document before performing key-based operations.
deleteKeyValue()  : array<string|int, mixed>|object
Deletes a value from an array or object using a dot-notated key path.
ensureKeyValue()  : array<string|int, mixed>|object
Ensures that one or more keys or properties exist in an array or object.
getKeyValue()  : mixed
Retrieves a value from an array or object using a dot-notated key path.
hasKeyValue()  : bool
Checks whether a given key or property exists in an array or object, including nested paths.
resolveReferencePath()  : mixed
Navigates to the parent container of the last key segment in a nested structure.
setKeyValue()  : array<string|int, mixed>|object
Sets a value in an array or object using a dot-notated key path.

Functions

assertDocumentKeyValid()

Validates the key, separator, and type of the provided document before performing key-based operations.

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

This internal helper ensures that:

  • The key is not empty.
  • The separator is not empty.
  • The document matches the expected type (array or object), or infers the type if $isArray is null.

If a mismatch between the inferred or forced type and the actual document type occurs, an InvalidArgumentException is thrown.

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

The input document (either an array or an object).

$key : string

The key or property name/path to validate.

$separator : string = '.'

The separator for nested paths (default is '.').

$isArray : bool|null = null

Optional reference: true for array, false for object, null to infer automatically.

Tags
throws
InvalidArgumentException

If the key or separator is empty, or the document type does not match $isArray.

example

Returns true:

$doc = ['foo' => 'bar'];
assertDocumentKeyValid( $doc , 'foo' ) ;

Returns false, sets $isArray = false

$doc = (object)['foo' => 'bar'];
assertDocumentKeyValid( $doc , 'foo' , '.' , $isArray ) ;

Returns true, sets $isArray = true

$doc = ['foo' => 'bar'];
assertDocumentKeyValid( $doc , 'foo' , '.' , $isArray ) ;

Throws InvalidArgumentException: "Key cannot be empty."

$doc = ['foo' => 'bar'];
assertDocumentKeyValid( $doc , '' , '.' ) ;

Throws InvalidArgumentException: "Separator cannot be empty."

$doc = (object)['foo' => 'bar'] ;
assertDocumentKeyValid( $doc , 'foo' , '' ) ;

Throws InvalidArgumentException: "Type mismatch: expected object, got array."

$doc = ['foo' => 'bar'];
assertDocumentKeyValid( $doc , 'foo' , '.' , false ) ;

Throws InvalidArgumentException: "Type mismatch: expected array, got stdClass."

$doc = new stdClass;
assertDocumentKeyValid( $doc , 'foo' , '.' , true ) ;
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
bool

Returns the resolved value of $isArray: true for array, false for object.

deleteKeyValue()

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

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

This utility supports:

  • Single key deletion (string)
  • Multiple key deletion (array of strings)
  • Flat keys (e.g., "name")
  • Nested keys (e.g., "user.profile.name")
  • Wildcard deletion for sub-containers (e.g., "user.*")
  • Global wildcard "*" to clear the entire document

The input can be an associative array or a stdClass-like object. Intermediate paths are ensured to exist before deletion.

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

The data source (array or object) to operate on.

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

The key path(s) to delete (e.g. "foo.bar" or ["foo.bar", "baz.*"]).

$separator : string = '.'

The separator used to split the key path. Defaults to '.'.

$isArray : bool|null = null

Optional: force array (true) or object (false) mode; if null, auto-detects.

$strict : bool = false

If true, throws exception when key doesn't exist. Default: false.

Tags
throws
InvalidArgumentException

If input is not array/object, if key is invalid, or if path traversal encounters a type mismatch. In strict mode, also throws if key doesn't exist.

example

Delete an single array key :

$doc = ['name' => 'Alice', 'age' => 30];
$doc = deleteKeyValue( $doc , 'age' ) ;
// Result: ['name' => 'Alice']
example

Delete multiple keys at once:

$doc = ['name' => 'Alice', 'age' => 30, 'email' => 'a@b.c'];
$doc = deleteKeyValue($doc, ['age', 'email']);
// Result: ['name' => 'Alice']
example

Delete multiple nested keys:

$doc = ['user' => ['name' => 'Alice', 'email' => 'a@b.c', 'age' => 30]];
$doc = deleteKeyValue($doc, ['user.name', 'user.age']);
// Result: ['user' => ['email' => 'a@b.c']]
example

Mix of simple and wildcard deletions:

$doc =
[
    'name' => 'Alice',
    'meta' => ['a' => 1, 'b' => 2],
    'config' => ['x' => 10, 'y' => 20]
];
$doc = deleteKeyValue($doc, ['name', 'meta.*']);
// Result: ['meta' => [], 'config' => ['x' => 10, 'y' => 20]]
example

Delete all properties with a wildcard key expression.

$doc = ['meta' => ['a' => 1, 'b' => 2]];
$doc = deleteKeyValue($doc, 'meta.*');
// Result: ['meta' => []]
example

Delete all object properties:

$doc = (object)['user' => (object)['name' => 'Alice', 'email' => 'a@b.c']];
$doc = deleteKeyValue($doc, 'user.*');
// Result: (object)['user' => (object)[]]
example

Non-strict mode (default) - ignore missing keys:

$doc = ['name' => 'Alice', 'age' => 30];
$doc = deleteKeyValue($doc, ['age', 'email', 'phone']); // no error
// Result: ['name' => 'Alice']
example

Strict mode - throws exception for missing keys:

$doc = ['name' => 'Alice', 'age' => 30];
try {
$doc = deleteKeyValue($doc, ['age', 'email'], strict: true);
} catch (InvalidArgumentException $e) {
echo $e->getMessage(); // "Key 'email' does not exist."
}
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>|object

The updated document after deletion.

ensureKeyValue()

Ensures that one or more keys or properties exist in an array or object.

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

Missing keys are created and initialized. Defaults can be defined globally or per key. Nested keys are supported using a separator (default: '.'). Intermediate path segments are created automatically if missing.

Features:

  • Specific Defaults: Pass an associative array to $keys to set different defaults per key.
  • Lazy Loading: Pass a Closure as a default value to calculate it only if needed.
  • Typed Properties: With $enforce = true, strictly checks initialized state of typed properties.
Parameters
$document : array<string|int, mixed>|object

The target document (array or object).

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

A single key, a list of keys ['a', 'b'], or an associative map ['key' => 'default'].

$default : mixed = null

Global default value (or Closure) for keys without a specific default. 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 to auto-detect.

$enforce : bool = false

Force initialization of non-initialized typed properties. Default: false.

Tags
throws
InvalidArgumentException

If the document or key definition is invalid.

example

Ensure simple keys with a global default :

$doc = [];
$doc = ensureKeyValue($doc, ['name', 'age'], null);
// Result: ['name' => null, 'age' => null]

Ensure keys with specific default values :

$doc = [];
$doc = ensureKeyValue($doc, [
'role' => 'guest',   // Specific default
'active'             // Uses global default (true)
], true);
// Result: ['role' => 'guest', 'active' => true]

Use a Closure for lazy evaluation (heavy calculation) :

$doc = [];
$doc = ensureKeyValue($doc, 'created_at', fn() => new DateTimeImmutable());
// Result: ['created_at' => object(DateTimeImmutable)]

Enforce initialization of typed properties (PHP 7.4+) :

class User { public string $name; } // Uninitialized
$doc = new User();

// Without enforce: Property exists, so it's skipped (remains uninitialized).
// With enforce: Detects uninitialized state and sets default.
$doc = ensureKeyValue($doc, 'name', 'Anonymous', '.', null, true);

// Result: User object with $name = 'Anonymous'

Use with named arguments (PHP 8+) to skip optional parameters:

$doc = new User();
// We skip separator and isArray to target 'enforce' directly
ensureKeyValue($doc, 'name', default: 'John', enforce: true);
author

Marc Alcaraz (ekameleon)

since
1.0.8
Return values
array<string|int, mixed>|object

The updated document with ensured keys.

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.

hasKeyValue()

Checks whether a given key or property exists in an array or object, including nested paths.

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

This helper determines if the specified key exists in the given document (array or object), supporting nested keys using a separator (default is '.').

Unlike isset(), this function considers keys with null values as existing. That means a key exists if it is present in the array/object, even if its value is null.

It can optionally force the document type (array or object) via the $isArray parameter.

If any part of the path does not exist, false is returned. This function does not rely on __get() or __isset() magic methods for objects.

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

The document (array or object) to inspect.

$key : string

The key or property path to check. Supports nesting with separator.

$separator : string = '.'

Separator used for nested paths. Default is '.'.

$isArray : bool|null = null

Optional: true if document is an array, false if object, null to auto-detect.

Tags
throws
InvalidArgumentException

If the document or key is invalid.

author

Marc Alcaraz (ekameleon)

since
1.0.0
example
$doc = ['name' => 'Alice' , 'empty' => null ];
hasKeyValue($doc, 'name'); // true
hasKeyValue($doc, 'empty'); // true
hasKeyValue($doc, 'age');  // false
$doc = ['user' => ['name' => 'Alice']];
hasKeyValue($doc, 'user.name'); // true
hasKeyValue($doc, 'user.age');  // false
$doc = (object)['user' => (object)['name' => 'Alice']];
hasKeyValue($doc, 'user.name'); // true
hasKeyValue($doc, 'user.age');  // false
$doc = [];
hasKeyValue($doc, 'config.debug.enabled'); // false
$doc = (object)[];
hasKeyValue($doc, 'meta.version.major'); // false
Return values
bool

True if the full key path exists, false otherwise.

resolveReferencePath()

Navigates to the parent container of the last key segment in a nested structure.

& resolveReferencePath(array<string|int, mixed>|object &$document, array<string|int, mixed> $keys, bool $isArray) : mixed

This function traverses through nested arrays or objects based on the provided key path, ensuring that each intermediate level exists. It returns a reference to the parent container that should contain the final key segment.

It is typically used to prepare for read/write operations on nested values.

Requires external helpers:

  • ensureArrayPath() (creates intermediate arrays)
  • ensureObjectPath() (creates intermediate objects)
Parameters
$document : array<string|int, mixed>|object

The root document to navigate through (passed by reference).

$keys : array<string|int, mixed>

The exploded path as array segments (e.g. ['user', 'profile', 'name']).

$isArray : bool

If true, treat the structure as arrays; if false, as objects.

Tags
example
$doc = [];
$keys = ['user', 'name'];
$ref = &resolveReferencePath($doc, $keys, true);
$ref['name'] = 'John';
// $doc is now: ['user' => ['name' => 'John']]
example
$doc = new stdClass();
$keys = ['config', 'theme'];
$ref = &resolveReferencePath($doc, $keys, false);
$ref->theme = 'dark';
// $doc is now: (object)['config' => (object)['theme' => 'dark']]
example

Mixed structure support:

$doc = ['data' => (object)['name' => 'Alice']];
$keys = ['data', 'age'];
$ref = &resolveReferencePath($doc, $keys, true);
$ref->age = 30;
// $doc is now: ['data' => (object)['name' => 'Alice', 'age' => 30]]
example

Overwriting scalars:

$doc = ['user' => 'not_an_array'];
$keys = ['user', 'profile', 'name'];
$ref = &resolveReferencePath($doc, $keys, true);
$ref['name'] = 'Alice';
// $doc is now: ['user' => ['profile' => ['name' => 'Alice']]]
see
ensureArrayPath()
see
ensureObjectPath()
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
mixed

Reference to the container (array or object) that should hold the final key.

setKeyValue()

Sets a value in an array or object using a dot-notated key path.

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

This function assigns a value to a key or property in the given array or object. It supports nested assignment using a separator (default: '.'). If any intermediate path segment does not exist, it is created automatically.

The type of the structure can be explicitly forced with $isArray, or inferred automatically.

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

The target array or object to modify.

$key : string

The key or property name to set. Supports nesting (e.g., "user.name").

$value : mixed

The value to assign.

$separator : string = '.'

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

$isArray : bool|null = null

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

Tags
throws
InvalidArgumentException

If the provided type does not match the structure type.

author

Marc Alcaraz (ekameleon)

since
1.0.0
example
$doc = ['name' => 'Alice'];
$doc = setKeyValue($doc, 'age', 30);
// Result: ['name' => 'Alice', 'age' => 30]
$doc = ['user' => ['name' => 'Alice']];
$doc = setKeyValue($doc, 'user.age', 30);
// Result: ['user' => ['name' => 'Alice', 'age' => 30]]
$doc = (object)['user' => (object)['name' => 'Alice']];
$doc = setKeyValue($doc, 'user.age', 30);
// Result: (object)['user' => (object)['name' => 'Alice', 'age' => 30]]
$doc = [];
$doc = setKeyValue($doc, 'config.debug.enabled', true);
// Result: ['config' => ['debug' => ['enabled' => true]]]
$doc = (object)[];
$doc = setKeyValue($doc, 'meta.version.major', 1);
// Result: (object)['meta' => (object)['version' => (object)['major' => 1]]]
Return values
array<string|int, mixed>|object

The updated document after the value has been set.


        
On this page

Search results