Example 1 — Check for No Error or Syntax Error
Decode a good and a bad JSON string, and read the error code after each one.
<?php
json_decode('{"ok":true}');
echo json_last_error(), PHP_EOL;
echo json_last_error() === JSON_ERROR_NONE ? 'No error' : 'Error', PHP_EOL;
json_decode('{oops}');
echo json_last_error(), PHP_EOL;
echo json_last_error() === JSON_ERROR_SYNTAX ? 'Syntax error found' : 'Other error', PHP_EOL; How It Works
- The first JSON string is valid, so json_last_error() returns 0.
- 0 is the value of JSON_ERROR_NONE, so the first message says No error.
- The second JSON string has no quotes around the key, so decoding fails.
- The code 4 matches JSON_ERROR_SYNTAX.

