PHP

Set Nested Value by Dot Path

admin by @admin ADMIN
4d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Mutate a nested array by dot path, auto-creating any intermediate arrays. Companion to getPath; together they replace a lot of isset+array_key_exists ladders.
PHP
Raw
<?php
function setPath(array &$arr, string $path, mixed $value): void {
    $cursor = &$arr;
    $segs   = explode('.', $path);
    $last   = array_pop($segs);
    foreach ($segs as $seg) {
        if (!isset($cursor[$seg]) || !is_array($cursor[$seg])) {
            $cursor[$seg] = [];
        }
        $cursor = &$cursor[$seg];
    }
    $cursor[$last] = $value;
}

$state = [];
setPath($state, 'user.profile.email', 'a@x.com');
setPath($state, 'user.profile.name',  'Alice');
print_r($state);
// [ user => [ profile => [ email => a@x.com, name => Alice ] ] ]
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.