How to loop through a JSON array in PHP?

If you’re working with JSON (JavaScript Object Notation) and either need to convert a JSON string to array or object and loop through it or vice-versa, take an array or object and convert it to a JSON string to return, both can be done in PHP or JavaScript.

I broke up this post into three sections:

Convert JSON String to PHP Array or Object

PHP >= 5.2.0 features a function,

<?php
  // Loop through Array
  $someArray = ...; // Replace ... with your PHP Array
  foreach ($someArray as $key => $value) {
    echo $value["name"] . ", " . $value["gender"] . "<br>";
  }

  // Loop through Object
  $someObject = ...; // Replace ... with your PHP Object
  foreach($someObject as $key => $value) {
    echo $value->name . ", " . $value->gender . "<br>";
  }
?>
1, that decodes a JSON string into a PHP variable. By default it returns an object. The second parameter accepts a boolean that when set as
<?php
  // Loop through Array
  $someArray = ...; // Replace ... with your PHP Array
  foreach ($someArray as $key => $value) {
    echo $value["name"] . ", " . $value["gender"] . "<br>";
  }

  // Loop through Object
  $someObject = ...; // Replace ... with your PHP Object
  foreach($someObject as $key => $value) {
    echo $value->name . ", " . $value->gender . "<br>";
  }
?>
2, tells it to return the objects as associative arrays. You can learn more about the
<?php
  // Loop through Array
  $someArray = ...; // Replace ... with your PHP Array
  foreach ($someArray as $key => $value) {
    echo $value["name"] . ", " . $value["gender"] . "<br>";
  }

  // Loop through Object
  $someObject = ...; // Replace ... with your PHP Object
  foreach($someObject as $key => $value) {
    echo $value->name . ", " . $value->gender . "<br>";
  }
?>
1 function from PHP’s documentation.

<?php
  // JSON string
  $someJSON = '[{"name":"Jonathan Suh","gender":"male"},{"name":"William Philbin","gender":"male"},{"name":"Allison McKinnery","gender":"female"}]';

  // Convert JSON string to Array
  $someArray = json_decode($someJSON, true);
  print_r($someArray);        // Dump all data of the Array
  echo $someArray[0]["name"]; // Access Array data

  // Convert JSON string to Object
  $someObject = json_decode($someJSON);
  print_r($someObject);      // Dump all data of the Object
  echo $someObject[0]->name; // Access Object data
?>

Loop through PHP Array or Object

Loop through a PHP array or object with a

<?php
  // Loop through Array
  $someArray = ...; // Replace ... with your PHP Array
  foreach ($someArray as $key => $value) {
    echo $value["name"] . ", " . $value["gender"] . "<br>";
  }

  // Loop through Object
  $someObject = ...; // Replace ... with your PHP Object
  foreach($someObject as $key => $value) {
    echo $value->name . ", " . $value->gender . "<br>";
  }
?>
4 loop.

<?php
  // Loop through Array
  $someArray = ...; // Replace ... with your PHP Array
  foreach ($someArray as $key => $value) {
    echo $value["name"] . ", " . $value["gender"] . "<br>";
  }

  // Loop through Object
  $someObject = ...; // Replace ... with your PHP Object
  foreach($someObject as $key => $value) {
    echo $value->name . ", " . $value->gender . "<br>";
  }
?>

Note the differences in accessing the values of an array vs an object.

Convert PHP Array or Object to JSON String

PHP also features a

<?php
  // Loop through Array
  $someArray = ...; // Replace ... with your PHP Array
  foreach ($someArray as $key => $value) {
    echo $value["name"] . ", " . $value["gender"] . "<br>";
  }

  // Loop through Object
  $someObject = ...; // Replace ... with your PHP Object
  foreach($someObject as $key => $value) {
    echo $value->name . ", " . $value->gender . "<br>";
  }
?>
5 function to convert an array or object into a string. Read more about the
<?php
  // Loop through Array
  $someArray = ...; // Replace ... with your PHP Array
  foreach ($someArray as $key => $value) {
    echo $value["name"] . ", " . $value["gender"] . "<br>";
  }

  // Loop through Object
  $someObject = ...; // Replace ... with your PHP Object
  foreach($someObject as $key => $value) {
    echo $value->name . ", " . $value->gender . "<br>";
  }
?>
5 function from PHP’s documentation.

<?php
  // Array
  $someArray = [
    [
      "name"   => "Jonathan Suh",
      "gender" => "male"
    ],
    [
      "name"   => "William Philbin",
      "gender" => "male"
    ],
    [
      "name"   => "Allison McKinnery",
      "gender" => "female"
    ]
  ];

  // Convert Array to JSON String
  $someJSON = json_encode($someArray);
  echo $someJSON;
?>

Note that I’m using the short array syntax that’s featured in PHP 5.4+.

<?php
  $array = array(
    "foo" => "bar",
    "bar" => "foo"
  );

  // as of PHP 5.4
  $array = [
    "foo" => "bar",
    "bar" => "foo"
  ];
?>


Convert JSON String to JavaScript Object

JavaScript has a built-in

<?php
  // Loop through Array
  $someArray = ...; // Replace ... with your PHP Array
  foreach ($someArray as $key => $value) {
    echo $value["name"] . ", " . $value["gender"] . "<br>";
  }

  // Loop through Object
  $someObject = ...; // Replace ... with your PHP Object
  foreach($someObject as $key => $value) {
    echo $value->name . ", " . $value->gender . "<br>";
  }
?>
7 method that parses a JSON string and returns an object.

<script>
  // Convert JSON String to JavaScript Object
  var JSONString = '[{"name":"Jonathan Suh","gender":"male"},{"name":"William Philbin","gender":"male"},{"name":"Allison McKinnery","gender":"female"}]';

  var JSONObject = JSON.parse(JSONString);
  console.log(JSONObject);      // Dump all data of the Object in the console
  alert(JSONObject[0]["name"]); // Access Object data
</script>

<?php
  // Loop through Array
  $someArray = ...; // Replace ... with your PHP Array
  foreach ($someArray as $key => $value) {
    echo $value["name"] . ", " . $value["gender"] . "<br>";
  }

  // Loop through Object
  $someObject = ...; // Replace ... with your PHP Object
  foreach($someObject as $key => $value) {
    echo $value->name . ", " . $value->gender . "<br>";
  }
?>
7 is very well-supported, but there are browsers that do not support it (i.e. <= IE 7. More information at ).

jQuery 1.x has a

<?php
  // Loop through Array
  $someArray = ...; // Replace ... with your PHP Array
  foreach ($someArray as $key => $value) {
    echo $value["name"] . ", " . $value["gender"] . "<br>";
  }

  // Loop through Object
  $someObject = ...; // Replace ... with your PHP Object
  foreach($someObject as $key => $value) {
    echo $value->name . ", " . $value->gender . "<br>";
  }
?>
9 method that should fill in the gaps for those browsers if you’re needing to support them. You can also use the JSON-js library as a polyfill.

<script>
  // Convert JSON String to JavaScript Object with jQuery
  var JSONString = "..."; // Replace ... with your JSON String

  var JSONObject = $.parseJSON(JSONString);
  console.log(JSONObject);      // Dump all data of the Object in the console
  alert(JSONObject[0]["name"]); // Access Object data
</script>

Loop through JavaScript Object

You can then loop through a JavaScript object using a

<?php
  // Array
  $someArray = [
    [
      "name"   => "Jonathan Suh",
      "gender" => "male"
    ],
    [
      "name"   => "William Philbin",
      "gender" => "male"
    ],
    [
      "name"   => "Allison McKinnery",
      "gender" => "female"
    ]
  ];

  // Convert Array to JSON String
  $someJSON = json_encode($someArray);
  echo $someJSON;
?>
0 loop.

<script>
  // Loop through Object
  var JSONObject = ...; // Replace ... with your JavaScript Object

  for (var key in JSONObject) {
    if (JSONObject.hasOwnProperty(key)) {
      console.log(JSONObject[key]["name"] + ", " + JSONObject[key]["gender"]);
    }
  }
</script>

Convert JavaScript Object to JSON String

JavaScript has a

<?php
  // Array
  $someArray = [
    [
      "name"   => "Jonathan Suh",
      "gender" => "male"
    ],
    [
      "name"   => "William Philbin",
      "gender" => "male"
    ],
    [
      "name"   => "Allison McKinnery",
      "gender" => "female"
    ]
  ];

  // Convert Array to JSON String
  $someJSON = json_encode($someArray);
  echo $someJSON;
?>
1 method to convert a value into a JSON string.

<script>
  var JSONObject = [
    {
      "name": "Jonathan Suh",
      "gender": "male"
    },
    {
      "name": "William Philbin",
      "gender": "male"
    },
    {
      "name": "Allison McKinnery",
      "gender": "female"
    }
  ];

  var JSONString = JSON.stringify(JSONObject);
  alert(JSONString);
</script>

Like

<?php
  // Array
  $someArray = [
    [
      "name"   => "Jonathan Suh",
      "gender" => "male"
    ],
    [
      "name"   => "William Philbin",
      "gender" => "male"
    ],
    [
      "name"   => "Allison McKinnery",
      "gender" => "female"
    ]
  ];

  // Convert Array to JSON String
  $someJSON = json_encode($someArray);
  echo $someJSON;
?>
2,
<?php
  // Array
  $someArray = [
    [
      "name"   => "Jonathan Suh",
      "gender" => "male"
    ],
    [
      "name"   => "William Philbin",
      "gender" => "male"
    ],
    [
      "name"   => "Allison McKinnery",
      "gender" => "female"
    ]
  ];

  // Convert Array to JSON String
  $someJSON = json_encode($someArray);
  echo $someJSON;
?>
1 is not supported in dinosaur browsers like <= IE 7. You can use the JSON-js library to polyfill
<?php
  // Array
  $someArray = [
    [
      "name"   => "Jonathan Suh",
      "gender" => "male"
    ],
    [
      "name"   => "William Philbin",
      "gender" => "male"
    ],
    [
      "name"   => "Allison McKinnery",
      "gender" => "female"
    ]
  ];

  // Convert Array to JSON String
  $someJSON = json_encode($someArray);
  echo $someJSON;
?>
1 as well.


You can combine the methods above to create powerful, dynamic implementations on your website or application.

Let’s say you want to get information from a database, safely return the data as JSON, and loop through it dynamically, you can do so with a bit of PHP and JavaScript with Ajax.

Dynamically Get JSON via Ajax and Loop Through JSON

Let’s assume your database structure looks like the following:

Table: people
┌────┬────────────────────┬─────────┐
| id | name               | gender  |
├────┼────────────────────┼─────────┤
| 0  | Jonathan Suh       | male    |
| 1  | William Philbin    | male    |
| 2  | Allison McKinnery  | female  |
| 3  | Becky Borgster     | female  |
| 4  | Victoria Einsteen  | female  |
└────┴────────────────────┴─────────┘

And you want to dynamically get a list of people from the database based on gender, like this:

How to loop through a JSON array in PHP?

Let’s start with the front-end file

<?php
  // Array
  $someArray = [
    [
      "name"   => "Jonathan Suh",
      "gender" => "male"
    ],
    [
      "name"   => "William Philbin",
      "gender" => "male"
    ],
    [
      "name"   => "Allison McKinnery",
      "gender" => "female"
    ]
  ];

  // Convert Array to JSON String
  $someJSON = json_encode($someArray);
  echo $someJSON;
?>
5 that’ll have a select dropdown with genders to select from, a table to display the results, and the script to handle the Ajax. The JavaScript is written in jQuery.

<select id="gender" name="gender">
  <option value="male">Male</option>
  <option value="female">Female</option>
</select>

<table id="people" border="1">
  <thead>
    <th>Name</th>
    <th>Gender</th>
  </thead>
  <tbody>

  </tbody>
</table>

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#gender").on("change", function() {
  $.ajax({
    type: "POST",
    data: {
      "gender": $("#gender").val()
    },
    url: "response.php",
    dataType: "json",
    success: function(JSONObject) {
      var peopleHTML = "";

      // Loop through Object and create peopleHTML
      for (var key in JSONObject) {
        if (JSONObject.hasOwnProperty(key)) {
          peopleHTML += "<tr>";
            peopleHTML += "<td>" + JSONObject[key]["name"] + "</td>";
            peopleHTML += "<td>" + JSONObject[key]["gender"] + "</td>";
          peopleHTML += "</tr>";
        }
      }

      // Replace table’s tbody html with peopleHTML
      $("#people tbody").html(peopleHTML);
    }
  });
});
</script>

Now let’s create a

<?php
  // Array
  $someArray = [
    [
      "name"   => "Jonathan Suh",
      "gender" => "male"
    ],
    [
      "name"   => "William Philbin",
      "gender" => "male"
    ],
    [
      "name"   => "Allison McKinnery",
      "gender" => "female"
    ]
  ];

  // Convert Array to JSON String
  $someJSON = json_encode($someArray);
  echo $someJSON;
?>
6 file to handle the back-end logic of getting the information from the database and returning the results as a JSON string.

<?php
  // Loop through Array
  $someArray = ...; // Replace ... with your PHP Array
  foreach ($someArray as $key => $value) {
    echo $value["name"] . ", " . $value["gender"] . "<br>";
  }

  // Loop through Object
  $someObject = ...; // Replace ... with your PHP Object
  foreach($someObject as $key => $value) {
    echo $value->name . ", " . $value->gender . "<br>";
  }
?>
0

To get a more in-depth and better example of PHP-JSON-JavaScript/jQuery-Ajax interaction, read my jQuery Ajax Call to PHP Script with JSON Return post.

What is the best way to loop through this array in PHP?

6 ways to loop through an array in php.
While loop. The while loop is very common loop among all languages and PHP is not different. ... .
do while Loop. Well, personally it's my least favorite loop in every programming language, so I'd probably say less. ... .
For Loop. ... .
Foreach Loop. ... .
array_walk. ... .
Array Iterator..

How do I iterate over an array in JSON?

1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.

How to loop through JSON object in PHP?

How to Iterate JSON Arrays in PHP Using a Recursive Function with GeoJSON.
Load and set your GeoJSON content into a PHP variable..
Use json_decode to convert the JSON content into a php multidimensional array..
Create a custom recursive function to iterate the JSON content..

How to loop through the array of JSON objects in PHP?

PHP and JSON.
The json_encode() function is used to encode a value to JSON format..
The json_decode() function is used to decode a JSON object into a PHP object or an associative array..
The json_decode() function returns an object by default. ... .
You can also loop through the values with a foreach() loop:.