php · level 2 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
turns an array into text you can save or send.
A file holds only text, so how do you save an array? Turn it into JSON, a plain text way of writing data that nearly every language understands. gives text like {"name":"Rex","age":4}.
turns it back. The true asks for arrays. Leave it out and you get an object instead, which square brackets cannot open. Broken JSON gives back null.
Pass JSON_PRETTY_PRINT to json_encode and the text is spread over lines, easier for people to read.
<?php
$path = sys_get_temp_dir() . "/pet.json";
$pet = ["name" => "Rex", "age" => 4, "tricks" => ["sit", "roll"]];
file_put_contents($path, json_encode($pet));
echo file_get_contents($path) . "\n";
$loaded = json_decode(file_get_contents($path), true);
echo "{$loaded["name"]} knows " . count($loaded["tricks"]) . " tricks\n"; JSON is also how most websites and apps send data to each other, so you will meet it everywhere.
guess first
A list and a labelled array. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
echo json_encode(["tea", "jam"]) . "\n";
echo json_encode(["drink" => "tea", "cups" => 2]) . "\n";
your turn
Your turn. Save your settings.
Type a theme, like dark or light, and a volume from 0 to 10. Run it to save the settings as JSON and load them back.
fix it
The book will not open. Can you fix it?
- Read the error:
Cannot use object of type stdClass as array. What didjson_decodegive back? - Without its second argument,
json_decodegives an object. Ask it for an array instead. - Change line 3 to
$book = json_decode($text, true);, then press run.
nailed it
your arrays can travel as text now. :D
json_encodeturns an array into JSON text.json_decode($text, true)turns it back into an array.- Save JSON in a file to keep whole arrays.
new words in your collection
- JSON
- json_encode
- json_decode
This lesson isn’t saved. A free account remembers every lesson you finish.