How can PHP developers efficiently search for a specific key within a multidimensional array in PHP?

When searching for a specific key within a multidimensional array in PHP, developers can use a recursive function to iterate through the array and check each key. This function should check if the current key matches the desired key, and if not, recursively call itself on any nested arrays.

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

// Example usage
$nestedArray = [
    'key1' => 'value1',
    'key2' => [
        'key3' => 'value3',
        'key4' => 'value4'
    ]
];

$result = searchKeyInArray($nestedArray, 'key3');
echo $result; // Output: value3