I am especially interested in testing the return value of preg_match开发者_Go百科, which can be 1, 0, or false.
$val === false;
Example:
0 === false; // returns false
false === false; // returns true
Use triple equals operator/strict comparison
Use ===
type comparison.
Check the manual: 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
The ===
checks for type as well as equality
so:
0 === false; //will return false
false === false; //will return true
preg_match() and preg_match_all() return the number of matches found, or false in case of an error. However this means it will return 0 if no matches are found so testing explicitly for false and then trying to loop through an empty set will still be problematic.
I usually test for false, then test again for match count before looping results. Something to the effect of:
$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');
}
Use the not operator !
to check for false: (! 0 === false)
is always false.
精彩评论