Parsing JSON array with PHP foreach

In PHP, you can parse JSON arrays using json_decode() and iterate through them with foreach. The json_decode() function converts JSON strings into PHP arrays or objects.

Syntax

json_decode($json_string, $associative = false)

Parameters

Parameter Description
$json_string The JSON string to decode
$associative When true, returns associative array instead of object

Example

Here's how to parse a JSON array and access its nested values using foreach ?

<?php
$json_array = '{
    "values": {
        "a": "abc",
        "d": 0,
        "efg": 349
    }
}';
$array = json_decode($json_array, true);
foreach($array as $values) {
    echo $values['efg'];
    echo $values['d'];
    echo $values['a'];
}
?>

Output

This will produce the following output ?

3490abc

Parsing Multiple Array Elements

When working with JSON arrays containing multiple objects, you can iterate through each element ?

<?php
$json_array = '[
    {"name": "John", "age": 30},
    {"name": "Jane", "age": 25}
]';
$array = json_decode($json_array, true);
foreach($array as $person) {
    echo "Name: " . $person['name'] . ", Age: " . $person['age'] . "<br>";
}
?>
Name: John, Age: 30
Name: Jane, Age: 25

Conclusion

Use json_decode() with the second parameter as true to get associative arrays, then iterate with foreach to access nested JSON data efficiently in PHP.

Updated on: 2026-03-15T08:39:14+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements