Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are all PHP equality comparisons symmetric?

Is $a == $b always equivalent to $b == $a?

I think in JavaScript there are a few weird cases where that's not true, due to casting.

I think ide is correct. I'll ask another question.

like image 300
mpen Avatar asked Jan 20 '11 21:01

mpen


1 Answers

In short, yes. $a == $b will always be the equivalent of $b == $a. There are some short comings, such as floats. Of course, you shouldn't be nesting two float for equality anyways.

EDIT
Concerning floats: If you had two float and compared them, they technically should be the same. However, floating point values which seem to have the same value do not need to actually be identical. So, if $a is a literal .69 and $b is the result of a calculation, they can very well be different, but both display the same value. This is why you should never compare floating-point values by using the ==.

If you need to compare floating-point values, you really need to use the smallest acceptable difference in your specific case. Something like this would work for comparing floats (setting our smallest acceptable difference at 0.000001):

if(abs($a-$b) < 0.000001) {
  //Same
}

PHP: abs - Absolute Value

like image 114
Michael Irigoyen Avatar answered Sep 23 '22 22:09

Michael Irigoyen