The Strpos Trap
The problem arises because if we simply check that there’s a positive return value from the function, we’ll miss the case where the string appears at the start of the other string since the character offset will be zero:
$tagline = "PHP Made Easy";
if(strpos(strtolower($tagline), 'php')) {
echo 'php tagline: ' . $tagline;
}
This code won’t find the “if” to be true, since strpos returns zero and PHP will type juggle that to be false (debates about dynamically typed languages can be saved for another day)
Correct Use of ===
This is a great example of where the === operator really helps, as it can tell the difference between false and zero:
$tagline = "PHP Made Easy";
if(false !== strpos(strtolower($tagline), 'php')) {
echo 'php tagline: ' . $tagline;
}
This time, we’ll correctly get into the “if” even if the string appears at the start of the other string.
Not a particularly complex example but I think one that is simple enough to serve as a reminder as to what that extra = is for!
Nice example though.
Type juggling can be quite tricky and lead to unexpected results as you did perfectly describe in your blog post. One should always check the manual to see the different type of return values and react accordingly.
Another pro tip: write a wrapper function for that behaviour and call that in your code :)