在PHP中,如果0 == false为true,而false == false为true,如何测试false?

时间:2011-04-13 21:26:34

标签: php preg-match

我对测试preg_match的返回值特别感兴趣,可以是1,0或false。

5 个答案:

答案 0 :(得分:14)

$val === false;

示例:

0 === false; // returns false
false === false; // returns true

Use triple equals operator/strict comparison

答案 1 :(得分:6)

使用===类型比较。 查看手册:http://www.php.net/manual/en/language.operators.comparison.php

答案 2 :(得分:3)

$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

答案 3 :(得分:0)

使用not运算符!检查错误:(! 0 === false)始终为false。

答案 4 :(得分:0)

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');
}
相关问题