Ways PHP Will Make You Cry - #1

PHP emulates the languages from which it was inspired except in subtle and potentially disastrous ways.

Take the strpos function for example.

From a method signature standpoint, this function is exactly the same as its C/C++ cousins. It differs ever so slightly in the return value. C returns -1 if the given substring is not found, but PHP returns FALSE.

Naive programmer that you are, you figured they would be the same:

1
2
3
4
if( strpos($str, 'substring') >= 0 )
echo "Yep!";
else
echo "Nope!";

This will always take the first branch.

So you get bit by this bug, and skim the documentation to realize that strpos returns FALSE when the string is not found. Fine. You curse PHP for being deceptively similar to every other curly brace, C-based language and resolve to spend more time in the documentation.

So you refactor:

1
2
3
4
if( strpos($str, 'substring') != FALSE )
echo "Yep!";
else
echo "Nope!";

Congratulations. You just traded one subtle bug for another, more insidious one. What if 'substring' is the first word in the string you are searching? strpos will helpfully return 0, which is then un-helpfully mangled into false. So the snippet will take the else branch even though the substring was found. Great.

Hint: use the !== operator.

Read the Warnings

This is a stupid example to illustrate stupid language semantics. Unfortunately, this kind of logic is often used in business critical sections of the app. Imagine you are a new developer doing maintenance on a legacy PHP app; in fact, this is the first time you’ve ever written PHP. And further imagine that instead of echoing “Yep” and “Nope” you are instead setting up database connections to either development or production. Imagine you screwed up this logic and then left for the weekend. Imagine that caused all production users to be pointed at the dev database. That gets snapped from production every night. True story.

Never trust a language with the !== operator.