-2

I faced the below scenario that happened with my web application. I need a exact reason and solution for this

<?php
$var = 0;
if ($var == "StringVal") {
    echo $var;
    echo "Wrong";
} else {
    echo "Right";
}
?>

these code must print

Right

, But it print

0Wrong

What are the possibilities of this problem ?

Sathish Kumar D
  • 274
  • 6
  • 20

2 Answers2

2

According to the official documentation:

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.

So var_dump(0 == "a"); Would return true as Php tries to parse "a" to a number, if the parsing fails which happens in this case, it returns 0 and then 0 is equal to 0. To overcome this compare the type as well using ===.

Hope this helps.

Osama Sayed
  • 1,993
  • 15
  • 15
1

Don't use == for comparison in php. Use === instead.

This way you enforce a type check and this will work as expected. See here for a PHP type comparison tables. There you see that a "Loose comparisons with ==" between e.g. 0 (int) and "php" (string) will return true. Which is not what one would expect.

cb0
  • 8,415
  • 9
  • 52
  • 80