3

Can somebody explain why in the first example below the comparison is returning false?

In the second example, you can see that just changing the first character it will return true instead.

What am I missing?

(1 != "1f9bb589-434d-46ce-9b0d-fe101619ce6f") -> bool(false)

vs

(1 != "2f9bb589-434d-46ce-9b0d-fe101619ce6f") -> bool(true)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
s7a8m
  • 51
  • 2
  • 1
    [official doc](https://www.php.net/manual/en/language.operators.comparison.php): Prior to PHP 8.0.0, if a string is compared to a number or a numeric string then the string was converted to a number before performing the comparison. This can lead to surprising results as can be seen with the following example: – Simone Rossaini Sep 29 '21 at 09:12

1 Answers1

4

The != operator performs a comparison with type juggling. Since the first operand is an int, the comparison is performed numerically, and the second operand is coerced to an int too. This means the first sequence of digits is taken and converted to an int, and everything after it is discarded. In the first example, the first sequence of digits is "1", so you get 1 != 1, which is obviously false. In the second example, you similarly get 1 != 2, which is obviously true.

Mureinik
  • 297,002
  • 52
  • 306
  • 350