When you're using the equality operator (==
), PHP performs type juggling if the two values are not of the same type. When comparing a number to a string, it will try to cast that string to a number.
When casting a string to a number, if the string starts with a valid numeric value, that will be used. As soon as a non-numeric value is encountered, PHP will stop processing the rest of the string (if the string doesn't start with a number, PHP will turn it into 0
). So your string "5 AND SOME TEXT"
starts with a valid numeric value (5
) but as soon as PHP finds that space it stops and you end up with the numeric value 5
. Since 5 == 5
, your result is true
. The same is true for your other string, "1.234 AND SOME TEXT"
is a valid number up to the first space.
There are two ways to work around this problem:
- Use the identical operator (
===
). This will ensure that no type juggling is done so the result of 5 === "5 AND SOME TEXT"
will be false
. The downside is that since you're comparing a numeric type to a string, the result of 5 === "5"
will also be false
since the two values are of different types. This may not be what you want.
- Cast your number to a string. Then, both values are strings and no type juggling takes place. You'll end up with
"5" == "5 AND SOME TEXT"
(or (string)5 == "5 AND SOME TEXT"
), both of which will be false
. But if the right side value is actually numerically correct, you'll get the result you want: "5" == "5"
(or (string)5 == "5"
) will return true
.