Parsing with json_decode()
Learn to convert a JSON string to a PHP value with json_decode().
The decode function turns a string into an array
The decode function converts a structured data format string into a PHP array or object. The key-value pairs in the string become array elements on the PHP side.
The second parameter, assoc, decides the result type. Pass true to get an associative array; pass false to get an object. In most cases, arrays are easier to work with, so true is preferred.
assoc=true gives an array, assoc=false gives an object
If you pass true to decode, the result is an associative array; you access values with square brackets like $data['product']. If you pass false, the result is an object; access uses an arrow, $data->product.
Both carry the same data; the difference is access style. Arrays are easier to loop over, so true is preferred for most API work.
Exercise Convert a string to an array and print a value
Convert the string in $text to an array with the decode function and assign it to $data. Pass true as the second parameter. Then print the value of $data['product'].
Show example solution
Call decode with $text and true, assign the result to $data; print the product key with echo.
Example solution:
$data = decode($text, true);
echo $data['product'];
Test yourself
-
The assoc parameter for an associative array
$text = '{"product":"Café","price":5}'; $data = decode($text, ____); echo $data['product'];Show answer
$text = '{"product":"Café","price":5}'; $data = decode($text, true); echo $data['product']; -
What type does decode($text, true) return?
- An object
- An integer
- An associative array
- A string
Show answer
An associative array — Correct. assoc=true makes decode return an associative array.
-
Match the decode concepts
- json_decode
- converts string to array
- assoc=true
- returns associative array
- assoc=false
- returns object
- $data['name']
- array element access