Oihana PHP

setKeyValue.php

Table of Contents

Functions

setKeyValue()  : array<string|int, mixed>|object
Sets a value in an array or object using a dot-notated key path.

Functions

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