strpos() >= 0 always evaluates as true [duplicate]
Asked Answered
T

4

5

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.

Truscott answered 28/3, 2014 at 18:16 Comment(0)
T
10

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.

Tychonn answered 28/3, 2014 at 18:18 Comment(0)
M
2

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)
Milagrosmilam answered 28/3, 2014 at 18:19 Comment(0)
T
2

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';

            }
Twinscrew answered 28/3, 2014 at 18:24 Comment(0)
T
1

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';
Tirol answered 28/3, 2014 at 18:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.