8

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.

4
  • Because 0 is considered empty (NULL) Commented Feb 1, 2013 at 21:25
  • 1
    use type safe comparison: === null Commented Feb 1, 2013 at 21:26
  • 1
    codepad.org/dWmodFRs Commented Feb 1, 2013 at 21:29
  • @PeterSzymkowski excellent example. Commented Feb 1, 2013 at 21:30

6 Answers 6

7

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)) {..}
Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

3

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);
}

Comments

2

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

Comments

1

Use the === comparator

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

3 Comments

comparator - where did you take such word? :-S It's an "operator", "comparator" is usually a comparison function passed to a sorting functions
English isn't my first language... I think I just mash Comparison Operators into a single word.
it's actually not about english, but about programming terms
1

Use the is_null() function.

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

Comments

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.