Bird
Raised Fist0
PHPprogramming~20 mins

JSON encoding and decoding in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
JSON Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this PHP code using json_encode?
Consider the following PHP code snippet. What will it output?
PHP
<?php
$array = ['name' => 'Alice', 'age' => 30, 'active' => true];
echo json_encode($array);
?>
A{"name":"Alice","age":30,"active":true}
B{"name":"Alice","age":"30","active":"true"}
C{"name":Alice,"age":30,"active":true}
DArray
Attempts:
2 left
💡 Hint
Remember json_encode converts PHP arrays to JSON strings with proper quotes and types.
❓ Predict Output
intermediate
2:00remaining
What does json_decode return with second parameter true?
What will be the output of this PHP code?
PHP
<?php
$json = '{"fruit":"apple","count":5}';
$result = json_decode($json, true);
var_dump($result);
?>
Aarray(2) { ["fruit"]=> string(5) "apple" ["count"]=> int(5) }
Bobject(stdClass)#1 (2) { ["fruit"]=> string(5) "apple" ["count"]=> int(5) }
Cstring(23) "{"fruit":"apple","count":5}"
DNULL
Attempts:
2 left
💡 Hint
The second parameter true makes json_decode return an associative array.
❓ Predict Output
advanced
2:00remaining
What error does this PHP code raise when decoding invalid JSON?
What error or output will this PHP code produce?
PHP
<?php
$invalidJson = '{"name":"Bob", age: 25}';
$result = json_decode($invalidJson);
if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_last_error_msg();
} else {
    var_dump($result);
}
?>
ANULL
BControl character error, possibly malformed UTF-8 characters
CSyntax error, malformed JSON
DSyntax error
Attempts:
2 left
💡 Hint
Look at the JSON string: keys must be quoted strings.
🧠 Conceptual
advanced
2:00remaining
Which option correctly encodes a PHP object to JSON with private properties?
Given a PHP class with private properties, which code snippet will correctly encode its public data to JSON?
PHP
<?php
class User {
    private string $name;
    private int $age;
    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }
    public function toArray(): array {
        return ['name' => $this->name, 'age' => $this->age];
    }
}
$user = new User('Eve', 28);
// Which line below correctly encodes the user data?
Aecho json_encode($user);
Becho json_encode($user->toArray());
Cecho json_encode(get_object_vars($user));
Decho json_encode((array)$user);
Attempts:
2 left
💡 Hint
Private properties are not accessible directly; use a method to expose data.
🚀 Application
expert
2:00remaining
How many items are in the array after decoding this JSON string?
Given this PHP code, how many items does the resulting array contain?
PHP
<?php
$json = '[{"id":1,"tags":["php","json"]},{"id":2,"tags":[]},{"id":3}]';
$array = json_decode($json, true);
echo count($array);
?>
A1
B2
C3
D0
Attempts:
2 left
💡 Hint
Count the top-level elements in the JSON array.

Practice

(1/5)
1. What does the PHP function json_encode() do?
easy
A. Converts PHP data into a JSON formatted string
B. Converts JSON string into PHP data
C. Validates JSON syntax
D. Reads JSON data from a file

Solution

  1. Step 1: Understand the purpose of json_encode()

    This function takes PHP variables like arrays or objects and converts them into a JSON string format.
  2. Step 2: Differentiate from json_decode()

    json_decode() does the opposite by converting JSON strings back to PHP data.
  3. Final Answer:

    Converts PHP data into a JSON formatted string -> Option A
  4. Quick Check:

    json_encode() = PHP to JSON string [OK]
Hint: json_encode() makes PHP data into JSON text [OK]
Common Mistakes:
  • Confusing json_encode() with json_decode()
  • Thinking json_encode() reads JSON from files
  • Assuming json_encode() validates JSON syntax
2. Which of the following is the correct syntax to decode a JSON string into a PHP array?
easy
A. $data = json_encode($jsonString, true);
B. $data = json_decode($jsonString, true);
C. $data = json_decode($jsonString);
D. $data = json_encode($jsonString);

Solution

  1. Step 1: Identify the function to decode JSON

    The function to convert JSON string to PHP data is json_decode().
  2. Step 2: Use the second parameter to get an array

    Passing true as the second argument returns an associative array instead of an object.
  3. Final Answer:

    $data = json_decode($jsonString, true); -> Option B
  4. Quick Check:

    json_decode() with true returns array [OK]
Hint: Use json_decode($json, true) for PHP arrays [OK]
Common Mistakes:
  • Using json_encode() instead of json_decode()
  • Omitting the second parameter to get an array
  • Passing true to json_encode() which is invalid
3. What will be the output of the following PHP code?
$arr = ['name' => 'Anna', 'age' => 25];
$json = json_encode($arr);
echo $json;
medium
A. {"name":"Anna","age":25}
B. Array
C. name: Anna, age: 25
D. Error: Cannot encode array

Solution

  1. Step 1: Understand json_encode output

    The function converts the PHP associative array into a JSON string with keys and values in double quotes.
  2. Step 2: Check the exact JSON string format

    The output is a JSON object string: {"name":"Anna","age":25} with escaped quotes when printed.
  3. Final Answer:

    {"name":"Anna","age":25} -> Option A
  4. Quick Check:

    json_encode() outputs JSON string [OK]
Hint: json_encode() outputs JSON string with quotes [OK]
Common Mistakes:
  • Expecting PHP array print instead of JSON string
  • Missing quotes around keys and values
  • Confusing output with plain text or error
4. Identify the error in this PHP code snippet:
$json = '{"fruit":"apple","count":3}';
$data = json_decode($json, true);
echo $data->fruit;
medium
A. json_decode cannot parse this JSON
B. Incorrect JSON string format
C. Missing second parameter in json_decode
D. Using object syntax on an array after json_decode

Solution

  1. Step 1: Check json_decode parameters

    The second parameter true makes json_decode return an associative array.
  2. Step 2: Accessing array with object syntax

    Using $data->fruit tries to access an object property, but $data is an array, so this causes an error.
  3. Final Answer:

    Using object syntax on an array after json_decode -> Option D
  4. Quick Check:

    json_decode(true) returns array, use $data['fruit'] [OK]
Hint: Use $data['key'] if json_decode(true) used [OK]
Common Mistakes:
  • Accessing array as object after json_decode(true)
  • Assuming JSON string is invalid
  • Forgetting to pass true for array output
5. You have a PHP array:
$data = ["id" => 101, "tags" => ["php", "json", "coding"]];

Which code correctly encodes this array to JSON and then decodes it back to a PHP object?
hard
A. $json = json_encode($data); $obj = json_decode($json, true);
B. $json = json_decode($data); $obj = json_encode($json);
C. $json = json_encode($data); $obj = json_decode($json);
D. $json = json_encode($data, true); $obj = json_decode($json, true);

Solution

  1. Step 1: Encode PHP array to JSON string

    Use json_encode($data) to convert the PHP array into a JSON string.
  2. Step 2: Decode JSON string back to PHP object

    Calling json_decode($json) without the second parameter returns a PHP object.
  3. Final Answer:

    $json = json_encode($data); $obj = json_decode($json); -> Option C
  4. Quick Check:

    Encode then decode without true returns object [OK]
Hint: json_decode() without true returns object [OK]
Common Mistakes:
  • Using json_decode before json_encode
  • Passing true to json_encode (invalid)
  • Decoding with true returns array, not object
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard