4 min read
Working with JSON
Prerequisites: Composer & packages
$data = ['name' => 'Ada', 'age' => 36];
$json = json_encode($data);
echo $json; // {"name":"Ada","age":36}
$decoded = json_decode($json, true); // true = return an array, not an object
echo $decoded['name']; // Ada
Common mistakes
- Forgetting the
truesecond argument tojson_decode— without it, you get anstdClassobject ($decoded->name), not an array ($decoded['name']), which trips up code expecting one or the other. - Not checking
json_last_error()after decoding untrusted input — malformed JSON returnsnullsilently otherwise.