How do I loop through JSON array
The code snippet provided in your source material attempts to iterate over a raw JSON string using PHP syntax that belongs to JavaScript (for (int $i...), $json.length). This is a common stumbling block when bridging the gap between frontend logic and backend frameworks like CodeIgniter. You cannot directly loop through a string as if it were an object; you must first parse the data into a native array structure before iteration becomes possible.
In PHP, the standard approach is to decode the JSON string using json_decode(). By default, this function returns an associative array where keys are strings and values are mixed types. If you need to access elements by their numeric index (like $data[0], $data[1]), you must pass true as the second argument to force a return of an indexed array.
Here is how you should correct the logic inside your Search controller:
class Search extends CI_Controller {
public function index()
{
$json = '[{"name": "John Doe", "address": "115 Dell Avenue, Somewhere"}, {"name": "Jane Doe", "address": "19 Some Road, Somecity"}]';
// Decode the JSON string into an array of objects
$data = json_decode($json, true);
// Check if decoding was successful before looping
if ($data !== null) {
foreach ($data as $person) {
echo htmlspecialchars($person['name']) . "<br>";
echo htmlspecialchars($person['address']) . "<br>";
echo htmlspecialchars($person['tel']) . "<br>";
echo htmlspecialchars($person['occupation']) . "<br><hr>";
}
} else {
// Handle invalid JSON gracefully
log_message('error', 'Invalid JSON format provided.');
}
$this->load->view('search_page');
}
}
The critical line here is $data = json_decode($json, true);. Without the second true argument, $data would be an array of objects. While accessing properties via $person['name'] works in that case, trying to use numeric indexing like $data[$i]['name'] might fail depending on PHP's internal key handling for associative arrays. Using true ensures you get a strictly indexed array, making the loop logic predictable and robust.
One significant pitfall to avoid is attempting to determine the length of the JSON string itself. In the original snippet, $json.length refers to the character count of the text, not the number of items in the list. Even if you corrected the syntax to PHP's strlen($json), that value would be hundreds of characters, leading to an infinite loop or out-of-bounds errors when accessing array indices. Always rely on count($data) or iterate using foreach to avoid manually managing indices.
Another consideration is error handling. The json_decode() function returns null if the input string is malformed rather than throwing an exception by default. It is good practice to check for this null return value immediately after decoding. If you are building a public API or handling user input, always wrap your JSON parsing logic in a try-catch block if you switch to strict mode (passing false as the second argument), which throws an exception on failure instead of returning null.
If you are moving away from CodeIgniter or looking for a more modern PHP stack, the Laravel framework handles JSON decoding and iteration with similar clarity but often offers additional helpers for API responses. The underlying logic remains consistent across frameworks: decode first, then iterate. For instance, in a Laravel application receiving a request body, you would typically access $request->json('data')->toArray() before looping, ensuring type safety from the start.
Ultimately, the choice between for loops and foreach depends on your needs, but foreach is generally preferred for JSON arrays because it abstracts away index management entirely. It reduces the risk of off-by-one errors and makes the code more readable. By decoding the string correctly first, you unlock the full power of PHP's array manipulation functions without needing to maintain manual counters or worry about string lengths.