1

If I run the following, no error is returned and the value of $result is INF. json_last_error() returns 0.

$result = json_decode('547533e683433', true);

As this is a string and not JSON I would expect $result to be NULL and json_last_error() to return 4 or JSON_ERROR_SYNTAX.

Why is this happening?

greg
  • 6,853
  • 15
  • 58
  • 71
  • Well, what do you expect it to return? – Anonymous Jun 11 '15 at 21:09
  • `547533e683433` is a *huge* number. 547533 x10^683433 – gen_Eric Jun 11 '15 at 21:11
  • I would expect json_last_error() to return an error code, in this case it should be 4 (JSON_ERROR_SYNTAX) and the $result to be NULL. I'll update the question. – greg Jun 11 '15 at 21:11
  • @RocketHazmat So huge, that PHP thinks it is infinitive and returns it as `INF` – Rizier123 Jun 11 '15 at 21:11
  • 2
    @greg: According to [the docs](http://php.net/json_decode), `[PHP] will also encode and decode scalar types and NULL`. So it's trying to decode `'547533e683433'` as an int, but it's so big that it gives you infinity. – gen_Eric Jun 11 '15 at 21:13
  • but it is a string, not a number? – greg Jun 11 '15 at 21:14
  • Not a full dupe: http://stackoverflow.com/q/19236155/3933332 – Rizier123 Jun 11 '15 at 21:14
  • @greg: It's a number. The `e` means "times `10^y`". So, `3e2` is `3x10^2`. See the docs for [`is_numeric`](http://php.net/manual/en/function.is-numeric.php): Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. – gen_Eric Jun 11 '15 at 21:15
  • @greg: Also when decoding, `'1'` is a number and `'"1"'` is a string. – gen_Eric Jun 11 '15 at 21:21
  • 1
    Why the down votes? It seems like a legitimate question to me? @RocketHazmat your answers have been great, add as an answer and I'll accept. – greg Jun 11 '15 at 21:22
  • @greg I think the problem was, that the users, didn't see what your question was/ what you wanted, so it might was unclear to them. (But sadly I'm out of votes for today, otherwise you and Rocket Hazmat would get an upV). – Rizier123 Jun 11 '15 at 21:29

1 Answers1

3

This is the expected result. While '547533e683433' is not valid JSON, PHP can still "decode" it.

PHP implements a superset of JSON as specified in the original RFC 4627 - it will also encode and decode scalar types and NULL.

According to the docs for json_decode, PHP will decode single scalar values, not just arrays/objects.

In the case of '547533e683433', it's interpreted as an int when decoding (strings need to be in double quotes). 547533e683433 is read as 547533 x 10^683433 (see the docs for is_numeric), which is a huge number. PHP can't represent a number this big, so it gives you INF.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337