Working with JSON in PHP

- 2 minutes read

A PHP array can be easily encoded in JSON format (and vice-versa).

Let’s begin by exploring how an array can be encoded to JSON.

Despite formally being called an array, PHP arrays are really more like maps. An array might look like something like this:

$array = array(
    'color' => 'red',
    'shape' => 'circle'
);
// OR
$array = [
    'color' => 'red',
    'shape' => 'circle'
];

Similarly to JavaScript’s JSON.stringify method, PHP’s json_encode built-in function will convert an array to a JSON string:

$string = json_encode($array);

The output of the above snippet will be a string that looks like this: { "color" : "red", "shape" : "circle" }.

Link to this section Decoding JSON strings in PHP

You can also decode JSON strings back to either an associative array or an object:

$json = json_decode($string, true); // Return associative array
$color = $json->{'color'}; // Returns "red"

$json = json_decode($string); // Return object
$color = $json['color']; // Returns "red"

As demonstrated in the above snippet, the approach to providing keys and accessing values depends on whether an associative array or object is returned.

Link to this section Conclusion

Working with JSON in PHP can be a very frustrating experience. Especially when trying to decode JSON from external sources.

But I hope this brief tutorial helped you to better understand which data formats are accepted for each operation!