2

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.

1 Answer 1

5

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

More on the comparison operators here.

Sign up to request clarification or add additional context in comments.

3 Comments

Then why if ($array == null) is satisfied.
Because it is typecasting the values to compare them. Try using $array === null. And have a look at php.net/manual/en/types.comparisons.php to see what PHP compares.
Thanks for example and explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.