PHP

Get Nested Value by Dot Path

admin by @admin ADMIN
Jun 19, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Read deeply-nested array values like Lodash _.get(). Use a "a.b.c" string instead of nested isset checks; returns a default on any missing segment.
PHP
Raw
<?php
function getPath(array $arr, string $path, mixed $default = null): mixed {
    $cursor = $arr;
    foreach (explode('.', $path) as $seg) {
        if (!is_array($cursor) || !array_key_exists($seg, $cursor)) return $default;
        $cursor = $cursor[$seg];
    }
    return $cursor;
}

$data = ['user' => ['profile' => ['email' => 'a@x.com']]];
echo getPath($data, 'user.profile.email');                // a@x.com
echo getPath($data, 'user.profile.phone', 'unknown');     // unknown
echo getPath($data, 'foo.bar.baz', 'fallback');           // fallback
Tags

Save your own code snippets

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