I am sure the array I test is null. Even doing var_dump(array)
prints array(0) { }
.
But the test $this->assertNull($array);
fails.
On the contrary when I test below code it enters if
condition :
if ($array == null) {
echo "Entered";
} else {
echo "Not Entered";
}
I don't understand why this is so. Please explain me if any one know the reason.
array(0) { }
is an empty array.
null
would the lack of an array at all.
They're not the same thing.
The problem with == is that it tries to type juggle the values to match them. An empty array is "falsy", as is null
.
If you want to see the difference, use ===
instead, which does not type juggle and also compares type;
$array1 = null;
$array2 = array();
if ($array1 == null) echo '1'; // $array1 is "similar to" null.
if ($array1 === null) echo '2'; // $array1 is null
if ($array2 == null) echo '3'; // $array2 is "similar to" null
if ($array2 === null) echo '4'; // $array2 is null
>>> 123