Karachi   ->   Sweden   ->   Karachi, again   ->   Dubai   ->   Bahrain   ->   Karachi, once more   ->   London and Leeds

Sunday, May 31, 2009

PHP: strpos() and the game of Booleans

Once you know a certain programming paradigm, learning different languages within that paradigm is a piece of cake, except for the idiosyncrasies of these languages. I wonder if there is any language without these!

So, while writing a game of hangman in PHP, I needed to use strpos() and was happy that the syntax matched C++.

int strpos (string $haystack, string $needle [, int $offset = 0])

However, if you have tried to match the result of strpos() in an if condition, you might have struck a brick wall:

The problem here is that strpos() can return an integer or a boolean false! That is, it either returns the position where the $selection is found in $word or it could return "false" if not found. At first sight, I couldn't believe that the return value can both be an integer or a boolean!

Now, in the code above, if the result of the strpos() call is 0, i.e., the very beginning of $word matches the $selection, the next if-condition will evaluate to true because 0 is equal to false in PHP. So, how do we match a varied data type with a single typed-value in PHP?

The solution to this is a strange === operator as documented in the strpos() API. There is a conjugate not operator which is written as !==.

Ah, the language designers! It's so un-intuitive that people have reported bugs around this very problem. And it's the same reason why some careful designers don't implement certain features.

How come one can write functions like the one below in PHP?