How to use JSON in PHP

JSON is a portable data format we use to represent data and send data from client to server.

Here’s an example of a JSON representation of an object that contains a string and a number:

  "name": "Flavio",
  "age": 35

PHP offers us two utility functions to work with JSON:

  • json_encode() to encode a variable into JSON
  • json_decode() to decode a JSON string into a data type (object, array…)


$test = ['a', 'b', 'c'];

$encoded = json_encode($test); // "["a","b","c"]" (a string)

$decoded = json_decode($encoded); // [ "a", "b", "c" ] (an array)

Download my free PHP Handbook!