strpos in PHP - like being stung by a needle in a haystack

In PHP when you have a string and want to find out if it contains another string, there are a few ways to do it. You can use regular expressions, use the strstr functions and a few other methods. The easiest way though is probably by using strpos, which returns the number of the character containing the first occurrence of the thing you’re looking for - and false if the string isn’t found.

Simple - yet with a slight danger.

$haystack = 'This is an example';
if (strpost('This', $haystack)) {
  echo "Found";
} else {
  echo "Not found";
}

In the example above, where we’re looking for the string “This”, the php code will echo “Not found”. The reason is, that the first (and only) occurrence of “This”, is at the begining of the string - character zero. As strpos returns zero, the if statement is evaluated to false and thus the “Not found” is echoed to the screen.

Fixing the error is simple once you remember the “the first index in a string is zero with strpos” rule:

$haystack = 'This is an example';
if (strpost('This', $haystack) !== false) {
  echo "Found";
} else {
  echo "Not found";
}

Adding the !== false, forces a type check, and as the number zero is (exactly) false, the value echoed is “Found”.