1

In the following code, I expect the if condition to be true, but actually the else condition is true. Can anyone explain the reason behind it?

$a = (float) 0;
$b = 0;
if ($b === $a) {
    echo "$a and $b are equal";
}
else{
    echo "$a and $b are not equal";  // true
}
Don't Panic
  • 39,820
  • 10
  • 58
  • 75
nik
  • 45
  • 9

2 Answers2

0

=== checks if the value (0 & 0) and type (int & float) are equal. In this case they are not.

If you want to only check the value and not the type then use ==

Bram
  • 19
  • 5
0

The else part is true because int(0) and float(0) is not equal when you try with ===, the if part will be true if you try with ==. See their datatype with var_dump($a) or var_dump($b)

=== not only compares value are equal but also ensures that entries are of same type

<?php
$a = (float) 0;
$b = 0;
var_dump($a);
var_dump($b);
if($b === $a){
    echo "$a and $b are equal";
}else{
    echo "$a and $b are not equal";  // true
}
?>
Always Sunny
  • 32,751
  • 7
  • 52
  • 86