strpos returns true always in php

user1765876 picture user1765876 · Mar 28, 2014 · Viewed 9k times · Source

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.

Any help in this regard,

Answer

hek2mgl picture hek2mgl · Mar 28, 2014

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.