What are the best practices for validating and processing JSON data in PHP to avoid errors like "Invalid argument supplied for foreach()"?

When working with JSON data in PHP, it is essential to validate the data before attempting to iterate over it using a foreach loop. This validation step helps prevent errors like "Invalid argument supplied for foreach()" that occur when trying to loop over non-iterable data. One way to validate JSON data is to use the json_decode function with the JSON_THROW_ON_ERROR flag, which will throw an exception if the JSON data is invalid.

// Validate and process JSON data
$jsonData = '{"key1": "value1", "key2": "value2"}';

try {
    $decodedData = json_decode($jsonData, true, 512, JSON_THROW_ON_ERROR);
    
    if (is_array($decodedData)) {
        foreach ($decodedData as $key => $value) {
            echo $key . ': ' . $value . "\n";
        }
    } else {
        throw new Exception('Invalid JSON data');
    }
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}