0

I'm new in PHP. I'm writing a function in PHP that uses preg_match. The function works well, but reading the official documentation on https://www.php.net/manual/en/function.preg-match.php I have a doubt. I found:

Warning This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

function sanitizeInputValue($val,$type){
 
        $tmpVal = trim($val);

        switch ($type)
            {
                case 'FIELD1':
                    
                    return is_numeric($tmpVal)==false ? "" : $val; 

                case 'FIELD2':
                    
                    return preg_match('/^[A-Z]$|^[A-Z]\d{1,3}$/', $tmpVal)==1 ? substr($val,0,4) : "";
                    
                case 'FIELD3':

                    return preg_match('/^[A-Z]$|^\d{3}$/', $tmpVal)==1 ? substr($val,0,3) : "";
                    
            }

        return "";
    }

So my question is, is it correct to test the return value of preg_match using operator == with 1 if the return value is true or 0 if the return value is false? Why does the documentation say that we have to use === operator?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • No; that will sometimes give you the wrong answer. If you instead use `==` operator, you sometimes won't get the result you expect, because in php there are various values that are `==` to `false`. For example, suppose you search for a pattern, and it returns `"0"` as a match. This is explained in the link that was added at top of your question. This is considered a duplicate question, because the answer is to understand the difference between `==` and `===` in php. Honestly, you should **almost never** use `==` in php. – ToolmakerSteve Apr 16 '22 at 23:03
  • In your case testing explicitely if `preg_match` returns 1 is totally useless with or without a strict comparison. Simply write: `return preg_match(...) ? bla : blu;`. No reason your patterns return a `false` and you are only interested by knowing if there's a match or not. – Casimir et Hippolyte Apr 21 '22 at 13:17

0 Answers0