Complete the code to convert an array to a JSON string.
<?php $array = ['name' => 'Alice', 'age' => 25]; $json = json_[1]($array); echo $json; ?>
The json_encode function converts a PHP array into a JSON string.
Complete the code to convert a JSON string back to a PHP array.
<?php $json = '{"name":"Bob","age":30}'; $array = json_[1]($json, true); print_r($array); ?>
The json_decode function converts a JSON string into a PHP variable. Passing true returns an associative array.
Fix the error in the code to correctly decode JSON into an object.
<?php $json = '{"city":"Paris","country":"France"}'; $obj = json_decode($json, [1]); echo $obj->city; ?>
Passing false or omitting the second argument returns an object. To access properties with ->, decode as an object.
Fill both blanks to encode an array and then decode it back to an associative array.
<?php $data = ['x' => 10, 'y' => 20]; $json = json_[1]($data); $array = json_[2]($json, true); print_r($array); ?>
First, use json_encode to convert the array to JSON. Then use json_decode with true to convert JSON back to an associative array.
Fill all three blanks to encode a nested array and decode it back as an object.
<?php $info = ['person' => ['name' => 'Eve', 'age' => 28]]; $json = json_[1]($info); $obj = json_[2]($json, [3]); echo $obj->person->name; ?>
Use json_encode to convert the array to JSON. Then use json_decode with false to decode JSON into an object, so you can access properties with ->.