Scott Hardie Scott Hardie -4 years ago 107
PHP Question

Why does "1" equal "+1"?

In PHP, the string "1" equals the string "+1" unless you do a strict comparison (===).

echo ("1" == "+1") ? "equals" : "not equals"; // result: "equals"

I'd prefer not to do a strict comparison, because the string "1" might be provided as an integer 1 in this case. I cannot do
to distinguish them because both return as 1, and I cannot do
to distinguish them because both return true.

So, two questions please:

  1. Is there any way to differentiate between these other than to convert the input to strings via
    and use strict comparison?

  2. Is this a bug or intended behavior in PHP? The reason doesn't seem mathematical ("2" does not equal "1+1" for instance, although "2" does equal "+2"). I'm curious as to the reasoning behind this.

Answer Source

When using == instead of === a loose comparison is used.

This often leads to types using truthyness when comparing incomparable types

have a look a the manual here to see the table of comparison

even though "+1" is not mentioned, it would be handled similarly to a '-1'

If you don't want this to happen, you do need to use ===

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download