3

The output of the code below is "fail" but if we pass 1 to $b as $b=1 then it will give the output as "pass". Can anybody tell me why this if condition holds true only for 0?

<?php 
      $a="abcd"; 
      $b=0; 
      if($a == $b)
      {
         echo "fail";
      } 
      else
      { 
         echo "pass";
      }
?>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
Jamie
  • 39
  • 2

4 Answers4

1

That is because of PHP type juggling with == operator. The full table is given here.

Alma Do
  • 37,009
  • 9
  • 76
  • 105
1

because you are comparing 2 variables of a different type, one of the 2 will be converted. In this case the string will be converted to an integer, which will be 0 for strings that do not start with a numeric value.

so "abc" == 0 in PHP, to add a type check use "abc" === 0

NDM
  • 6,731
  • 3
  • 39
  • 52
0

You're a victim of type juggling. Try using the identical comparison operator, ===, which also checks to make sure the types of variables are the same:

var_dump('abcd' === 0); // bool(false)
George Brighton
  • 5,131
  • 9
  • 27
  • 36
0

From the PHP Manual:

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

if($a==$b) { 
    echo "fail";
} 
else { 
    echo "pass";
}

This will output fail.

But, if you use the identical comparison operator ===, the type conversion does not take place:

if($a===$b) { 
    echo "fail";
} 
else { 
    echo "pass";
}

This will output pass.

For more details, refer to the type juggling documentation in the PHP manual.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150