Iterating Over JSON Arrays in PHP
When you receive a JSON string containing an array of objects, the immediate goal is usually to transform that text into something your application can manipulate. In PHP, this means decoding the string into an associative array and then iterating over it. The process is straightforward, but understanding how the data is structured after decoding prevents common iteration errors.
The most robust approach begins with json_decode. This function converts a JSON string into a PHP variable. Crucially, you must pass the second argument as true to receive a native PHP array rather than an object. If you omit this flag or set it to false, you get a stdClass object where keys are accessed via properties (e.g., $data[0]->var1). While objects work with loops using get_object_vars() or specific property access, arrays allow for cleaner syntax and are generally preferred when the structure is known to be an array.
Here is how you load and iterate over a standard JSON response:
$jsonString = '[{"var1": "9", "var2": "16", "var3": "16"}, {"var1": "8", "var2": "15", "var3": "15"}]';
// Decode into an array of objects (stdClass)
$data = json_decode($jsonString, false);
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
// Handle JSON decode errors here
throw new Exception('Invalid JSON provided');
}
foreach ($data as $item) {
echo "var1: {$item->var1}<br>";
echo "var2: {$item->var2}<br>";
}
In this example, the loop iterates over the decoded structure. Each $item is treated as an object because json_decode was called with false. The syntax $item->property reflects the original JSON keys. This approach works well if you are processing a stream of data where type safety isn't strictly enforced by a framework.
However, once you move into modern PHP development, particularly within a Laravel application, the pattern shifts slightly. When using Laravel's HTTP client to fetch data or when interacting with external APIs that return JSON responses, the framework often handles the decoding automatically via the response->json() method. This returns a collection of objects that can be iterated similarly:
$response = Http::get('https://api.example.com/data');
$items = $response->json();
foreach ($items as $item) {
// Access properties directly
$value = $item['var1'];
}
Note that accessing keys via square brackets ([]) or arrows (->) often works interchangeably in these collections, but sticking to one style improves readability. If you prefer working with native arrays regardless of the source, passing true to json_decode() is still the safer bet for custom scripts outside of framework-managed responses.
Performance Considerations
For large datasets, performance matters. If you are processing thousands of records, avoid using foreach if you can process each item immediately without storing them in memory. However, for typical API responses containing a few dozen items, the overhead is negligible. The real bottleneck usually lies in network latency or database queries triggered inside the loop, not the iteration itself. Always ensure that heavy operations (like saving to a database) are batched rather than performed one-by-one inside a tight loop if possible.
Common Pitfalls
A frequent mistake involves assuming the decoded data is always an array. If the JSON response contains a single object instead of an array, json_decode returns a single object. Attempting to use foreach on that variable will result in a warning because it is not iterable. Always check if the decoded value is an array or handle the non-array case explicitly before looping.
Additionally, be mindful of type juggling. JSON numbers are parsed as integers or floats in PHP unless they look like strings. If your JSON contains "var1": "9" (with quotes), it becomes a string. If it were "var1": 9, it becomes an integer. Your iteration logic should account for these differences to avoid errors when performing mathematical operations or strict type comparisons.
