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";
}
?>
If json_decode returns null is it because the database. json is not valid. You can fix this by open the database.
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.
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.
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.
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";
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With