Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does json_decode return null for empty array?

Tags:

json

php

decode

Why would this echo "NULL"? In my would it would be decoded to an empty array.

Is it something obvious I'm missing?

<?php

$json = json_encode(array());
$json_decoded = json_decode($json, true);
// same with json_decode($json);

if ($json_decoded == null){
    echo "NULL";
} else
{
    echo "NOT NULL";
}

?>
like image 565
netdigger Avatar asked Jun 13 '12 11:06

netdigger


People also ask

Why is json_decode returning null?

If json_decode returns null is it because the database. json is not valid. You can fix this by open the database.

What does json_decode return?

The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively. The NULL is returned if JSON can't be decoded or if the encoded data is deeper than the recursion limit.

What is the difference between json_encode and json_decode?

I think json_encode makes sure that php can read the . json file but you have to specify a variable name, whereas with json_decode it's the same but you have to specify a file name.

What does json_encode return?

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.


2 Answers

This is because array()==NULL. It does not check the object type in this case.

gettype(null) returns null, whereas

gettype(array()) returns array. Hope you got the difference.

Probably what you need is

if ($json_decoded === null) {
   echo "NULL";
} else
{
   echo "NOT NULL";
}
like image 76
gopi1410 Avatar answered Oct 15 '22 23:10

gopi1410


print_r the $json_decoded value it gives the empty array back. :)

$json = json_encode(array());
$json_decoded = json_decode($json, true);


if ($json_decoded == null){
    print_r($json_decoded);
} else
{
    echo "NOT NULL";
}

outputs : Array ( ) This is because with == operator the empty array gets type juggled to null

like image 26
Mithun Satheesh Avatar answered Oct 15 '22 22:10

Mithun Satheesh