Why does json_decode return null for empty array?

netigger picture netigger · Jun 13, 2012 · Viewed 13.1k times · Source

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";
}

?>

Answer

gopi1410 picture gopi1410 · Jun 13, 2012

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";
}