Vahid
Vahid

Reputation: 3442

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.

Upvotes: 8

Views: 10128

Answers (6)

Anirudh Ramanathan
Anirudh Ramanathan

Reputation: 46728

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)) {..}

Upvotes: 7

Sammitch
Sammitch

Reputation: 32232

Use the is_null() function.

if ( $i < 0 || is_null($i) ) {

Upvotes: 1

nimlhug
nimlhug

Reputation: 121

Use the === comparator

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

Upvotes: 1

Baba
Baba

Reputation: 95101

You need to compare types

var_dump($i == null); //true
var_dump($i === null); //false

You can use

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

Upvotes: 3

Kermit
Kermit

Reputation: 34054

You're comparing if 0 == null are equal, not identical, which is the same according to the documentation:

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

Upvotes: 3

zerkms
zerkms

Reputation: 254886

That's because you use ==. And as long as one operand is null - then another is implicitly casted to boolean 0 -> false

http://php.net/manual/en/language.operators.comparison.php

bool or null anything Convert to bool, FALSE < TRUE

Upvotes: 2

Related Questions