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
  • 41,125
  • 10
  • 61
  • 80
nik
  • 55
  • 1
  • 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
}
?>
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103