Convert JSON to Array in PHP with Online Demo

by Vincy. Last modified on October 27th, 2022.

This tutorial covers the basic details of the PHP json_encode function. It gives examples of decoding JSON string input to a PHP array.

It also describes this PHP JSON function‘s conventions, rules and limitations. First, let’s see a quick example of converting JSON to an array.

Convert JSON to PHP Array

This example has a JSON string that maps the animal with its count. The output of converting this JSON will return an associative array.

It uses PHP json_decode() with boolean true as its second parameter. With these decoding params, the JSON will be converted into a PHP array.

Quick example

<?php
// JSON string in PHP Array
$jsonString = '{"Lion":101,"Tiger":102,"Crocodile":103,"Elephant":104}';
$phpArray = json_decode($jsonString, true);

// display the converted PHP array
var_dump($phpArray);
?>

Output

array(4) {
  ["Lion"]=>
  int(101)
  ["Tiger"]=>
  int(102)
  ["Crocodile"]=>
  int(103)
  ["Elephant"]=>
  int(104)
}

See this online demo to get the converted array result from a JSON input.
View demo

See the diagram that shows the input JSON string and the output stdClass object of the JSON decoding. In the previous article, we have seen examples of the reverse operation that is converting a PHP array to a JSON string.
php json to array

PHP json_decode()

This native PHP function decodes the JSON string into a parsable object tree or an array. This is the syntax of this function.

json_decode(
    string $json,
    ?bool $associative = null,
    int $depth = 512,
    int $flags = 0
): mixed
  1. $json – Input JSON string.
  2. $associative – a boolean based on which the output format varies between an associative array and a stdClass object.
  3. $depth – the allowed nesting limit.
  4. $flag – Predefine constants to enable features like exception handling during the JSON to array convert.

You can find more about this function in the official documentation online.

Convert JSON to PHP Object

This program has a minute change of not setting the boolean flag to the PHP json_decode function. This will return a PHP stdClass object tree instead of an array.

<?php
// JSON string in PHP Array
$jsonString = '{"name":"Lion"}';

$phpObject = json_decode($jsonString);
print $phpObject->name;
?>

Output

Lion

Common mistakes during conversion from JSON to Array

The following JSON string is a valid JSON object in JavaScript, but not here in PHP. The issue is the single quote. It should be changed to a double quote.

If you want to see the JavaScript example to read and display JSON data the linked article has the code.

<?php
// 1. key and value should be within double quotes
$notValidJson = "{ 'lion': 'animal' }";
json_decode($notValidJson); // will return null

// 2. without a quote is also not allowed
$notValidJson = '{ lion: "animal" }';
json_decode($notValidJson); // will return null

// 3. should not have a comma at the end
$notValidJson = '{ "lion": "animal", }';
json_decode($notValidJson); // will return null
?>

How to convert JSON with large integers

This can be achieved by setting the bitmask parameter of the predefined JSON constants.

The JSON_BIGINT_AS_STRING constant is used to convert JSON with data having large integers.

<?php
$jsonString = '{"largeNumber": 12345678901234567890123}';

var_dump(json_decode($jsonString, false, 512, JSON_BIGINT_AS_STRING));
?>

Output

object(stdClass)#1 (1) {
  ["number"]=>
  string(20) "12345678901234567890123"
}

How to get errors when using json_decode

The function json_last_error() is used to return details about the last error occurrence. The following example handles the possible error cases of this PHP JSON function.

<?php
$jsonString = '{"Lion":101,"Tiger":102,"Crocodile":103,"Elephant":104}';
json_decode($jsonString);

switch (json_last_error()) {
    case JSON_ERROR_DEPTH:
        echo 'Error: Nesting limit exceeded.';
    break;
    case JSON_ERROR_STATE_MISMATCH:
        echo 'Error: Modes mismatch.';
    break;
    case JSON_ERROR_CTRL_CHAR:
        echo 'Error: Unexpected character found.';
    break;
    case JSON_ERROR_SYNTAX:
        echo 'Error: Syntax error, invalid JSON.';
    break;
    case JSON_ERROR_UTF8:
        echo 'Error: UTF-8 characters incorrect encoding.';
    break;
    default:
        echo 'Unexpected error.';
    break;
}
?>

SURPRISE! JSON to Array and Array to JSON conversion is not symmetrical

<?php
 $jsonString = '{"0": "No", "1": "Yes"}';
 	// convert json to an associative array
    $array = json_decode($jsonString, true); 
    print json_encode($array) . PHP_EOL;
?>

Output

["No","Yes"]

The PHP object is now changed to a PHP array. You may not expect it.

Encode -> Decode -> Encode

The above will not return the data to its original form.

The output of decoding to PHP arrays and encoding from PHP arrays are not always symmetrical. But, the output of decoding from stdClass objects and encoding to stdClass objects are always symmetrical.

So if you have plans to do cyclical conversion between the PHP array and a JSON string, then first convert the PHP array to an object. The convert the JSON.

View demo

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page