Your task is very simple. You need to check if a config tag is set to the color green. At first, you come up with the following solution:
$colorTag = 'color_green';
$actualColor = 'green';
if (strpos($colorTag, $actualColor)) {
return true;
}
The job is done and now you can reward yourself with a hot coffe. After a while you realize that your application background is not green anymore and you don’t know why. You are pretty sure that somebody messed up while administrating the app and you start asking people about what was changed since it last worked.
After a while you find out that color_green
was changed to green
because it doesn’t make sense to have two names with the same meaning. You are still not getting why it is not working as intended.
As we all know, strpos
returns the position of a needle in a haystack,if found, and false
if the needle is not found. The catch is that the first position is 0
, and 0 == false
.
If we write it like this, it automatically make sense:
$colorTag = 'green';
$actualColor = 'green';
$position = strpos($colorTag, $actualColor); // 0
if ($position != false) {
return true;
}
To keep away from this types of bugs you should always be explicit about what you are checking and always use strict comparisons:
if (strpos($haystack, $needle) !== false)
If you think that using ===/!==
is too much because none of your Python or Java friends are using them, then you neeed to memorize the loose comparisons table.