|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2021-12-01 14:40 UTC] joaquimsb89 at gmail dot com
Description:
------------
When using the json_decode() function and passing an integer as the first parameter, or with the strval() function, the return value is the integer itself instead of an expected NULL, expecting "Syntax error" as the error description.
Behaviour observed in the following environments:
PHP 7.4.26, debian 10/buster, installed via deb sury repo
PHP 8.0.13, Arch Linux, installed via pacman -S php
PHP 8.1.0, debian 11/bullseye, installed via deb sury repo
Test script:
---------------
<?php
var_dump(json_decode('', true));
var_dump(json_last_error_msg());
echo "\n";
var_dump(json_decode(123, true));
var_dump(json_last_error_msg());
echo "\n";
var_dump(json_decode(strval(123), true));
var_dump(json_last_error_msg());
echo "\n";
var_dump(json_decode('{"a":123}', true));
var_dump(json_last_error_msg());
Expected result:
----------------
NULL
string(12) "Syntax error"
NULL
string(12) "Syntax error"
NULL
string(12) "Syntax error"
array(1) {
["a"]=>
int(123)
}
string(8) "No error"
Actual result:
--------------
NULL
string(12) "Syntax error"
int(123)
string(8) "No error"
int(123)
string(8) "No error"
array(1) {
["a"]=>
int(123)
}
string(8) "No error"
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Nov 14 22:00:01 2025 UTC |
I am not aiming to start an argument, so I won't post more messages. But I believe some clarification might help. Thanks for your understanding, ---- Won't this behaviour cause, then, a potential error when processing external requests (like API calls) as we won't be able to retrieve a "valid JSON object" that can be converted to an object via json_decode($payload, false) or to an array via json_code($payload, true)? Even the official PHP website does not have an example for any input payload that is not a JSON-parsed string format, including {} and / or [] and bearing in mind the "key":"value" format. https://www.php.net/json_decode If the RFC 8259 is implemented as expected, then it looks like there's a lack of documentation on the PHP website (that leads to confusion) to cover these cases. Also, the PHP website points that the implemented logic is for RFC 7159 - which is being adjusted by the RFC 8259, so it's unfair point to "another RFC" than the one mentioned on the website. Extra reading would be appreciated here. Would be possible getting directions on where other examples can be found, please, so it's possible to contrast this specific case?As noted above, this is just a type juggling. If you want to be sure that passing number fails, declare strict types. Without that declared, the example var_dump(json_decode(123, true)); is basically just var_dump(json_decode('123', true));