How can a recursive function be used to navigate through a complex array structure in PHP?

When dealing with a complex array structure in PHP, a recursive function can be used to navigate through the array and access its nested elements. This is particularly useful when the array has multiple levels of nesting, as a recursive function can iterate through each level until the desired element is found.

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

// Example usage
$array = [
    'key1' => 'value1',
    'key2' => [
        'key3' => 'value3',
        'key4' => [
            'key5' => 'value5'
        ]
    ]
];

$result = navigateArray($array, 'key5');
echo $result; // Output: value5