Julian Wolfe
Julian Wolfe

Reputation: 43

Searching for a value and returning its path in a nested associative array in PHP

I'm trying to search for a value in a nested associative array in PHP, much like array_search but nested. I need all the keys leading to that particular value.

I didn't see anything on SO asking for help with this specific function, so now I am asking. Other examples seem to return all values in an array, not just the path to a single key/value pair.

Upvotes: 4

Views: 758

Answers (1)

deceze
deceze

Reputation: 522382

function array_search_path($needle, array $haystack, array $path = []) {
    foreach ($haystack as $key => $value) {
        $currentPath = array_merge($path, [$key]);
        if (is_array($value) && $result = array_search_path($needle, $value, $currentPath)) {
            return $result;
        } else if ($value === $needle) {
            return $currentPath;
        }
    }
    return false;
}

$arr = [
    'foo' => 'bar',
    'baz' => [
        'test' => 42,
        'here' => [
            'is' => [
                'the' => 'path'
            ]
        ],
        'wrong' => 'turn'
    ]
];

print_r(array_search_path('path', $arr));

// Array
// (
//    [0] => baz
//    [1] => here
//    [2] => is
//    [3] => the
// )

Upvotes: 3

Related Questions