Why are strings "0e368798" and "00000000" equal, per PHP's equality operator?

StackOverflow https://stackoverflow.com/questions/20770330

  •  21-09-2022
  •  | 
  •  

Frage

Can someone explain why the following two statements return true?

if ('0e368798' == '00000000')

or

if ((string)'0e368798' == (string)'00000000')

Why do I have to use the strict operator to check the equality of these two strings?

War es hilfreich?

Lösung

Because XeY is X * 10^(Y), and 0 times anything is 0. 0000000 is also 0. And == in PHP very intuitively thinks that if it can be converted into a number, it should be.

EDIT: It was in a helpful comment that is now deleted, so with apologies to the commenter whose name I did not catch, I will repeat it here - from PHP docs on comparison:

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top