In PHP, how can one determine which array should be considered as the "parent" array when searching in a multidimensional array?

When searching in a multidimensional array in PHP, it is important to determine which array should be considered as the "parent" array to properly access the nested arrays. One way to do this is by using a recursive function that checks if a key exists in the current array, and if not, continues searching in the nested arrays until the key is found. By keeping track of the parent array during the search process, you can accurately determine the hierarchy of the arrays.

function searchInMultidimensionalArray($array, $key) {
    foreach ($array as $k => $value) {
        if ($k === $key) {
            return $value;
        }
        if (is_array($value)) {
            $result = searchInMultidimensionalArray($value, $key);
            if ($result !== null) {
                return $result;
            }
        }
    }
    return null;
}

// Example of how to use the function
$parentArray = [
    'key1' => 'value1',
    'key2' => [
        'nested_key1' => 'nested_value1',
        'nested_key2' => 'nested_value2'
    ]
];

$result = searchInMultidimensionalArray($parentArray, 'nested_key1');
echo $result; // Output: nested_value1