How can PHP functions like foreach() be used to navigate through nested arrays efficiently?

When navigating through nested arrays in PHP, the foreach() function can be used to efficiently iterate over each level of the array. By using a recursive approach, we can handle arrays of any depth without needing to know the exact structure beforehand. This allows for flexible and dynamic navigation through nested arrays.

function navigateNestedArray($array) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            navigateNestedArray($value); // recursively call the function for nested arrays
        } else {
            echo "Key: $key, Value: $value" . PHP_EOL;
        }
    }
}

$array = [
    "key1" => "value1",
    "key2" => [
        "nested_key1" => "nested_value1",
        "nested_key2" => "nested_value2"
    ]
];

navigateNestedArray($array);