0
0
PHPprogramming~10 mins

JSON encoding and decoding in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to convert an array to a JSON string.

PHP
<?php
$array = ['name' => 'Alice', 'age' => 25];
$json = json_[1]($array);
echo $json;
?>
Drag options to blanks, or click blank then click option'
Astringify
Bdecode
Cparse
Dencode
Attempts:
3 left
💡 Hint
Common Mistakes
Using json_decode instead of json_encode.
Trying to use json_parse or json_stringify which do not exist in PHP.
2fill in blank
medium

Complete the code to convert a JSON string back to a PHP array.

PHP
<?php
$json = '{"name":"Bob","age":30}';
$array = json_[1]($json, true);
print_r($array);
?>
Drag options to blanks, or click blank then click option'
Adecode
Bstringify
Cparse
Dencode
Attempts:
3 left
💡 Hint
Common Mistakes
Using json_encode instead of json_decode.
Not passing true as the second argument to get an array.
3fill in blank
hard

Fix the error in the code to correctly decode JSON into an object.

PHP
<?php
$json = '{"city":"Paris","country":"France"}';
$obj = json_decode($json, [1]);
echo $obj->city;
?>
Drag options to blanks, or click blank then click option'
A0
Bfalse
Cnull
Dtrue
Attempts:
3 left
💡 Hint
Common Mistakes
Passing true and then trying to access properties with -> instead of array keys.
Passing null which defaults to false but can be confusing.
4fill in blank
hard

Fill both blanks to encode an array and then decode it back to an associative array.

PHP
<?php
$data = ['x' => 10, 'y' => 20];
$json = json_[1]($data);
$array = json_[2]($json, true);
print_r($array);
?>
Drag options to blanks, or click blank then click option'
Aencode
Bdecode
Cparse
Dstringify
Attempts:
3 left
💡 Hint
Common Mistakes
Using json_decode first or in the wrong order.
Not passing true to json_decode to get an array.
5fill in blank
hard

Fill all three blanks to encode a nested array and decode it back as an object.

PHP
<?php
$info = ['person' => ['name' => 'Eve', 'age' => 28]];
$json = json_[1]($info);
$obj = json_[2]($json, [3]);
echo $obj->person->name;
?>
Drag options to blanks, or click blank then click option'
Aencode
Bdecode
Cfalse
Dtrue
Attempts:
3 left
💡 Hint
Common Mistakes
Passing true to json_decode and then trying to access properties with ->.
Using json_decode before json_encode.