w3resource

PHP json_last_error() function

Introduction

In this page, you will learn about PHP json_last_error() function with examples.

Description

While working on encoding or decoding JSON, if an error occur, json_last_error() function returns the last error.

PHP version

PHP 5 >= 5.3.0

Syntax:

 json_last_error ()

Parameters:

json_last_error() function does not have any parameters.

Return values

json_last_error() function returns an integer.

The following table shows the values which are CONSTANTS :

Constants Description
JSON_ERROR_NONE Specifies that no error occurred.
JSON_ERROR_DEPTH Specifies that the maximum stack depth has been exceeded.
JSON_ERROR_STATE_MISMATCH Indicates that the associated JSON is not properly formed or invalid.
JSON_ERROR_CTRL_CHAR Indicates that the error is in control characters. This usually happens incorrect encoding.
JSON_ERROR_SYNTAX Indicates that this is a syntax error.
JSON_ERROR_UTF8 Indicates that error occurred due to malformed UTF-8 characters, which usually happens because of incorrect encoding.

json_last_error() example

<?php
 $w3r_json[] = "{'Website': 'w3resource.com'}";
//since we have used "'" instead of double quote (""), it is a syntax error.
 foreach ($w3r_json as $w3r_string) {
json_decode($w3r_string);
 switch (json_last_error()) {
case JSON_ERROR_NONE:
 echo ' - No errors';
 break;
 case JSON_ERROR_DEPTH:
 echo ' - Maximum stack depth exceeded';
 break;
 case JSON_ERROR_STATE_MISMATCH:
 echo ' - Underflow or the modes mismatch';
 break;
 case JSON_ERROR_CTRL_CHAR:
 echo ' - Unexpected control character found';
 break;
 case JSON_ERROR_SYNTAX:
 echo ' - Syntax error, malformed JSON';
 break;
 case JSON_ERROR_UTF8:
 echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
 break;
 default:
 echo ' - Unknown error';
 break;
 }
 echo PHP_EOL;
 }
?>
 

Output of the above example

json_last_error-function-output w3resource

Previous: PHP json_encode function
Next: Working with JSON and JavaScript



Follow us on Facebook and Twitter for latest update.