QA
Beginner LevelPHP 8+

How do json_encode() and json_decode() work and why is the second parameter in json_decode($json, true) critical?

❓ Interview Prompt: Explain JSON serialization in PHP, stdClass objects vs associative arrays in json_decode, and JSON_THROW_ON_ERROR.

'json_encode()' and 'json_decode()' convert between PHP data structures and JSON strings:

'json_decode($json, $associative)':

•
Default ('json_decode($json)'): Decodes JSON objects into PHP 'stdClass' objects ('$data->key').
•
Associative Mode ('json_decode($json, true)'): Passing 'true' decodes JSON objects into standard PHP Associative Arrays ('$data["key"]').

Best Practice - Error Handling (PHP 7.3+):

Pass the 'JSON_THROW_ON_ERROR' flag to throw a catchable 'JsonException' when decoding invalid JSON payloads instead of failing silently!

Code Implementation Example

php
<?php
$json = '{"name": "Alice", "role": "admin"}';

// 1. Decode into Associative Array (2nd parameter = true)
$arr = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
echo $arr['name']; // Outputs: Alice

// 2. Encode PHP Array back to JSON string
$data = ['status' => 'success', 'code' => 200];
$jsonStr = json_encode($data, JSON_PRETTY_PRINT);
echo $jsonStr;
💡Decoding JSON payloads to associative arrays and encoding arrays to formatted JSON strings.
🎯 Interview Key Takeaway

Pass true as the 2nd argument to json_decode() to decode JSON objects into PHP associative arrays.

#JSON#json_encode#json_decode#Beginner
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?