What are some common pitfalls when accessing multidimensional arrays in PHP, especially when using foreach loops?

One common pitfall when accessing multidimensional arrays in PHP, especially when using foreach loops, is not properly checking if the current element is an array before attempting to iterate over it. This can lead to errors or unexpected behavior if a non-array value is encountered. To solve this issue, you can use the is_array() function to check if the current element is an array before proceeding with the foreach loop.

$array = [
    'key1' => ['value1', 'value2'],
    'key2' => 'not an array',
    'key3' => ['value3', 'value4']
];

foreach ($array as $key => $value) {
    if (is_array($value)) {
        foreach ($value as $item) {
            echo $item . "<br>";
        }
    } else {
        echo $value . "<br>";
    }
}