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?
No comments:
Post a Comment