Skip to main content

The Language APIs Speak

APIs exchange data as JSON — text like {"id": 1, "name": "Ana"}. PHP translates in both directions with two built-in functions: json_encode turns a value into JSON text, json_decode turns JSON text back into PHP data.

Associative arrays are the natural carrier: the array's keys become the JSON keys, exactly as written. Passing true as the second argument of json_decode asks for arrays back (instead of objects) — the examples here always do.


From Array to JSON

json_encode produces compact JSON for machines; the JSON_PRETTY_PRINT flag produces readable JSON for humans and logs. Dropping empty fields is your call to make: filter them out of the array before encoding.

Encode, compact and pretty

Ana has no email, and the filter removes the empty field from her JSON entirely. Ben's full record prints indented.

Prompt
Write a PHP script that builds a user as an associative array, filters out its empty fields and encodes it compactly with json_encode, then encodes a full user with the JSON_PRETTY_PRINT flag, printing both JSON results.
Output: PHP script

From JSON to Data

json_decode parses JSON into arrays. Unknown JSON keys are not dropped — they ride along as extra entries your code is free to ignore; missing keys are simply absent, so read them with ?? and a default. Bad JSON returns null, and json_last_error_msg() tells you why — always check before trusting the result.

Decode and the extra key

The JSON carries an extra key the code never asked for — no error, it simply appears in the decoded array, as the key list shows. Broken JSON, on the other hand, returns null with a real error message.

Prompt
Write a PHP script that decodes a JSON string carrying an extra unknown key with json_decode, printing the id, the name and the full key list, and then tries to decode broken JSON and prints the message from json_last_error_msg.
Output: PHP script

Nested Data

Real API payloads nest: an order carries its user and a list of items. Arrays inside arrays map to JSON automatically — a keyed array becomes a JSON object, a list becomes a JSON array — no special handling needed.

An order with a user inside

The nested user array becomes a nested JSON object, the items list becomes a JSON array — the shape of the PHP data is the shape of the JSON.

Prompt
Write a PHP script with an order as an associative array holding an id, a list of item names and a nested user array. Encode it with json_encode and JSON_PRETTY_PRINT and print it to show nested objects and arrays.
Output: PHP script