Skip to content
AgileLogics
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 true second argument to json_decode — without it, you get an stdClass object ($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 returns null silently otherwise.