[英]In PHP, if 0==false is true, and false==false is true, how to test for false?
我特別感興趣的是測試preg_match的返回值,它可以是1,0或false。
使用===
類型比較。 查看手冊: http : //www.php.net/manual/en/language.operators.comparison.php
$num === 0; //is true if $num is 0 and is an integer
$num === 0; //is false if $num is 0 and is a string
===
檢查類型和相等性
所以:
0 === false; //will return false
false === false; //will return true
preg_match()和preg_match_all()返回找到的匹配數,如果發生錯誤則返回false。 但是,這意味着如果沒有找到匹配項,它將返回0,因此顯式測試為false然后嘗試循環一個空集仍然會有問題。
我通常測試為false,然后在循環結果之前再次測試匹配計數。 有效的東西:
$match = preg_match_all($pattern, $subject, $matches);
if($match !== false)
{
if(count($matches) > 0)
{
foreach($matches as $k=>$v)
{
...
}
}
else
{
user_error('Sorry, no matches found');
}
}
else
{
die('Match error');
}
使用not運算符!
檢查false:( (! 0 === false)
始終為false。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.