简体   繁体   中英

Why does “1|2” == 1 return true in PHP?

Why does this code return True instead of False?

"1|2" == 1

why doesn't it return False?

attention : 1|2 is string.

Your string "1|2" is cast to an integer for the comparison with integer 1.

According to PHP's type casting rules , casting strings to integers takes all leading digits from the string up to the first non-digit (giving 1 , and ignoring |2 because | is the first non-digit.

1 == 1 is true

When converted into a number "1|2" becomes 1 as the cast processes the string until the first non-numerical character. 1 == 1 so this is true. Strings are converted into numbers during == comparisons

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.

http://php.net/manual/en/language.operators.comparison.php

If you want to fix it use the === operator which will also check types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM