APIs and modern front ends speak JSON. PHP converts arrays/objects to JSON strings and back with json_encode and json_decode.
Encoding
$data = ['ok' => true, 'items' => [1, 2]];
$json = json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
Decoding
$parsed = json_decode($json, true); // associative array
// omit true for stdClass object
Common flags
JSON_THROW_ON_ERROR turns failures into exceptions. JSON_PRETTY_PRINT helps debugging. Always set Content-Type: application/json when returning JSON from real endpoints.
Important interview questions and answers
- Q: json_decode second parameter?
A:truereturns associative arrays;false(default) returnsstdClassobjects. - Q: Why JSON_THROW_ON_ERROR?
A: Silentfalsereturns hide malformed input—exceptions fail fast in APIs.
Self-check
- What type do you get from
json_decode($s, true)? - When would you prefer objects over arrays for decoded JSON?
Pitfall: Enable JSON_THROW_ON_ERROR in APIs—silent false from json_decode hides malformed payloads.