Why does (0 == 'Hello') return true in PHP?

后端 未结 5 1381
南方客
南方客 2020-12-03 16:53

Hey, if you have got the following code and want to check if $key matches Hello I\'ve found out, that the comparison always returns true

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 17:15

    Because PHP does an automatic cast to compare values of different types. You can see a table of type-conversion criteria in PHP documentation.

    In your case, the string "Hello" is automatically converted to a number, which is 0 according to PHP. Hence the true value.

    If you want to compare values of different types you should use the type-safe operators:

    $value1 === $value2;
    

    or

    $value1 !== $value2;
    

    In general, PHP evaluates to zero every string that cannot be recognized as a number.

提交回复
热议问题