簡體   English   中英

為什么我的If語句接受PHP中不正確的String條件?

[英]Why is my If statement accepting an incorrect String condition in PHP?

我很困惑,因為PHP接受以下條件。

<?php
   $b = true;
   if($b == 'anything') 
      echo 'ok';
   else
      echo 'no';
?>

好吧,PHP顯示ok 我仍然不知道怎么可能。

也許,你可以為我澄清一下。

這對你有用

$b = true;
if($b === 'hello') 
    echo 'ok';
else
    echo 'no';

當使用== php只會檢查值是否相等,而不比較值類型,當第一個值是bool時,php會將兩邊轉換為bool,轉換任何字符串但空字符串''和字符串'0'將返回true ,這就是為什么必須使用===

按照此鏈接了解php中的比較

Php不是嚴格類型的語言,因此IF語句后半部分的值被視為Truthy值。 如果你想抱怨類型也使用“===”比較。 查看此頁面上的真實表。 http://php.net/manual/en/types.comparisons.php

據對比較運算符PHP手冊( http://php.net/manual/en/language.operators.comparison.php==對於“equalness”,而檢查===身份檢查(這實際上意味着它是相同的TYPE和相同的VALUE)。

當比較(為了相等) boolstringstring被轉換為bool 根據文件

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM