We participate in the Amazon Service LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com

strpos gotcha!
$string1 = 'php is fun!';
$string2 = 'php';
if (strpos($string1,$string2)) {
 echo "\"" . $string1 . "\" contains \"" . $string2 . "\"";
} else {
 echo "\"" . $string1 . "\" does not contain \"" . $string2 . "\"";
}

 

This classic PHP problem asks if the output of this code will be correct, and why. It tests your knowledge of 2 things at the same time.The first is the behavior of the strpos function. The second is equality vs identity. The strpos function returns the position within the haystack where the first character of the needle is located if a match is found, or false if it is not found. In this case, the match is found at the first position, which due to the fact that PHP indexes are zero based, will be 0. So, the if statement will be:

if(0)

That will of course evaluate to false. So how do we fix it? We want to use the !== operator to look specifically for the return value to not be false. That way anything else will be considered true.

if(strpos($string1,$string2) !== false)

Understanding how == and === work, as well as when and where to use them is very important.