Oihana PHP

resolveReferencePath.php

Table of Contents

Functions

resolveReferencePath()  : mixed
Navigates to the parent container of the last key segment in a nested structure.

Functions

resolveReferencePath()

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

& resolveReferencePath(array<string, mixed>|object &$document, array<int, string> $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, mixed>|object

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

$keys : array<int, string>

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']]
$doc = new stdClass();
$keys = ['config', 'theme'];
$ref = &resolveReferencePath($doc, $keys, false);
$ref->theme = 'dark';
// $doc is now: (object)['config' => (object)['theme' => 'dark']]

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]]

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()
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.

On this page

Search results