PHP › JSON Handling in PHP

How do you convert a JSON formatted string back into a PHP array or object using json_decode?

Beginner

Answer

The json_decode function parses a JSON formatted string and converts it back into a corresponding PHP value, returning a PHP object by default, or an associative array if you pass true as the second argument, letting you easily work with JSON data received from an external API or submitted in a request body using familiar PHP array or object syntax.
$json = '{"name": "Ali", "age": 30}';
$data = json_decode($json, true);
echo $data['name'];
Real-world example An application receiving a webhook notification from a third party payment provider uses json_decode to parse the incoming JSON payload into a PHP array, immediately making the payment details easily accessible for further processing.

Common follow-ups: What is the difference between decoding JSON as an object versus as an associative array?;What does json_decode return if the input string is not valid JSON?