Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Compare Integer/String Variable with Null

I have an Integer/String variable. If I have an error in mysqli statement it becomes String and without errors it becomes number of affected rows (Integer).

But in PHP if we have something like this:

$i = 0;
if ( $i < 0 || $i == null ) {
    var_dump($i);
}

We have this result:

int 0

First, I want to know why this happens? (I mean, if var_dump is int 0, why the if statement doesn't work?)

Second, I want the solution for my comparison.

like image 638
Vahid Avatar asked Jun 12 '26 10:06

Vahid


1 Answers

You aren't doing a strict comparison. Use === instead of ==.

== will convert types and then compare

Use one of the below instead. is_null is the cleanest IMO.

if ( $i < 0 || $i === null ) {..}

OR

if ( $i < 0 || is_null($i)) {..}
like image 54
Anirudh Ramanathan Avatar answered Jun 13 '26 22:06

Anirudh Ramanathan