Reputation: 3442
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
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
Reputation: 121
Use the === comparator
if ( $i < 0 || $i === null ) {
var_dump($i);
}
Upvotes: 1
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
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
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