In PHP, if 0 == false is true and false == false is true, how can I check false?

I am particularly interested in checking the return value of preg_match, which can be 1, 0 or false.

+4
source share
5 answers
$val === false; 

Example:

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

Use the triple equals / strict comparison operator

+14
source

Use a comparison of type === . Check out the manual: http://www.php.net/manual/en/language.operators.comparison.php

+6
source
 $num === 0; //is true if $num is 0 and is an integer $num === 0; //is false if $num is 0 and is a string 

=== checks type as well as equality

So:

  0 === false; //will return false false === false; //will return true 
+3
source

Use the not ! Operator to check for false: (! 0 === false) always false.

0
source

preg_match () and preg_match_all () return the number of matches found or false in case of an error. However, this means that it will return 0 if no matches are found, so checking explicitly for false, and then trying to loop through an empty set will still be problematic.

Usually I check false and then check the number of matches again before the loop results. Sort 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'); } 
0
source

Source: https://habr.com/ru/post/1347992/


All Articles