我很困惑,因爲PHP接受以下條件。爲什麼我的If語句在PHP中接受不正確的String條件?
<?php
$b = true;
if($b == 'anything')
echo 'ok';
else
echo 'no';
?>
那麼,PHP顯示ok
。我仍然不明白怎麼可能。
也許,你可以幫我解釋清楚。
我很困惑,因爲PHP接受以下條件。爲什麼我的If語句在PHP中接受不正確的String條件?
<?php
$b = true;
if($b == 'anything')
echo 'ok';
else
echo 'no';
?>
那麼,PHP顯示ok
。我仍然不明白怎麼可能。
也許,你可以幫我解釋清楚。
Php不是嚴格類型的語言,因此IF語句後半部分的值被視爲Truthy值。如果您想要投訴類型,請使用「===」比較。看看這個頁面上的真理表。 http://php.net/manual/en/types.comparisons.php
據對比較運算符(http://php.net/manual/en/language.operators.comparison.php)==
檢查「equalness」,而===
檢查身份(這實際上意味着它是相同類型的,並且相同的值)PHP手冊。
當比較(爲了平等)a bool
和string
時,string
被鑄造爲bool
。按照docs:
When converting to boolean, the following values are considered FALSE: * the boolean FALSE itself * the integer 0 (zero) * the float 0.0 (zero) * the empty string, and the string "0" * an array with zero elements
所以你的字符串'anything'
變得true
。
PHP是一種鬆散的類型語言,因此可能發生鑄造。儘可能使用嚴格比較'$ b ==='hello'// false'。 http://php.net/manual/en/language.types.type-juggling.php – PeeHaa 2014-10-02 12:46:07
將'$ b'設置爲'true',然後給'$ b'賦值都是符合'真實性'的條件。如果你需要一個嚴格的比較,請使用'===' – 2014-10-02 12:46:34
[how-do-php-equality-double-equals-and-identity-triple-equals-comp](http://stackoverflow.com/questions/80646/how-do-the-php-equality-double-equal-and-identity-triple-equals-comp) – mithunsatheesh 2014-10-02 12:48:54