PHP json_last_error() function

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 :

ConstantsDescription
JSON_ERROR_NONESpecifies that no error occurred.
JSON_ERROR_DEPTHSpecifies that the maximum stack depth has been exceeded.
JSON_ERROR_STATE_MISMATCHIndicates that the associated JSON is not properly formed or invalid.
JSON_ERROR_CTRL_CHARIndicates that the error is in control characters. This usually happens incorrect encoding.
JSON_ERROR_SYNTAXIndicates that this is a syntax error.
JSON_ERROR_UTF8Indicates 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

Please Google+, Like this tutorial on FaceBook, Tweet, save it as bookmark and subscribe with our Feed. Have suggestions? comment using Disqus down this page. Thanks.

share with delicious share with facebook w3r rss  share with digg share with reddit share with stumbleupon share with twitter