What potential pitfalls should be considered when using foreach loops to iterate through JSON data in PHP?

One potential pitfall when using foreach loops to iterate through JSON data in PHP is that the data may not be in the expected format, leading to errors or unexpected behavior. To mitigate this, it's important to first decode the JSON data into an associative array using json_decode() with the second parameter set to true. This ensures that the data is structured as an array that can be easily iterated through with a foreach loop.

$jsonData = '{"key1": "value1", "key2": "value2"}';
$arrayData = json_decode($jsonData, true);

foreach ($arrayData as $key => $value) {
    echo $key . ': ' . $value . PHP_EOL;
}