Search code examples
phpstringstrpos

strpos() >= 0 always evaluates as true


I wrote this code:

$token="Birth";
$msg="I am awesome and I know it";

if (strpos(strtolower($msg), strtolower($token)) >= 0) {
    echo 'ok';
}

It prints ok

As we can see there is no word like Birth in the message, but still it returns true. I guess it should return false as the php manual says.


Solution

  • strpos() returns FALSE if the token was not found and the (first) position of the token in string if it was found. You need to check for boolean FALSE using the strict comparison operator === to identify if a token was found in a string or not:

    if(strpos(strtolower($msg),strtolower($token)) !== false){
        echo 'ok';
    } else {
        echo 'not ok';
    }
    

    This is because of PHP's loose typing system. If you use >=0, and the token was not found, PHP would cast the FALSE return value of strpos to 0 before the >= operation. And 0 >=0 evaluates to TRUE.