Question

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,

Was it helpful?

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.

OTHER TIPS

strpos() returns false if the token is not found. By checking if the result is greater than or equal to zero false is converted to an integer which becomes zero. So zero equals zero making your if statement true.

To fix this just see if strpos() returns false:

if(strpos(strtolower($msg),strtolower($token)) !== false)

Be careful with strpos:

strpos returns the position (number) if the corresponding string is present in the provided variable, or the boolean FALSE if it's not present at all. So if you say if(strpos(...)>=0), it would always evaluate to true because even boolean FALSE evaluates to 0. The best way to achieve this functionality is use the hard compare. Just say

if(strpos(strtolower($msg),strtolower($token)) !== FALSE){
// The above line will tell PHP that treat the condition as passed 
// only when strpos does not return The boolean FALSE.
            echo 'ok';

            }

This is because of php autocasting. You need to check type also with triple comparsion.

Do it like this:

$token="Birth";
$msg="I am awesome and I know it";
if(strpos(strtolower($msg),strtolower($token)) !== false)
  echo 'ok';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top