May 14

All too often, I see code like this, attempting to test if a particular string is found in a variable:

$test = 'abc123';
if(strpos($test, 'abc')) {
    // do comething
}

This statement is actually a common mistake, because the strpos() function returns the integer position of the first found letter in the string searched for. So in this example, strpos() would return integer ‘0′, because the string ‘abc’ starts at the very beginning of the string (the ‘0th’ position). And just like C/C++, when you put ‘0′ in a IF statement, it gets evaluated as FALSE. So although the string ‘abc’ has indeed been found in the $test variable, the IF statement will not be evaluated as such, because the match occured at the beginning of the string and ‘0′ was returned. Instead, you must use the strict triple comparison operator to test if the strpos() function has returned FALSE (string not found).

The code should look like this instead:

$test = 'abc123';
if(strpos($test, 'abc') !== false) {
    // do comething
}

So if the strpos() function does NOT return boolean FALSE (string not found), we know the string has indeed been found in the variable we are testing for. The IF statement will execute, even if the string begins at the ‘0th’ position.