PHP loose typing quiz
Some time ago there was a topic on the daily WTF about a bit of PHP code which was rather funny.
if (!count($items)>0) { something(); }
On first instance this looks rather normal, but it doesn’t exactly do what you think it does. When you read it, you might assume the “!” will invert the expression “count($items)>0″. This however is false, what get’s inverted is “count($items)”.
The reason this is funny, is because it actually does work. We want the full expression to be TRUE when there are zero items in $items. When count($items) is 0, this get’s converted to a boolean for the “!”, which will be FALSE. The “!” kicks in and it get’s flipped to TRUE. Then we are asking if TRUE is larger then 0. Now TRUE get’s converted to 1, or the right side 0 to FALSE, it doesn’t really matter. The end result is that we are asking if 1>0, which is TRUE.
So to show in code, what happens is something like this.
if (!count($items)>0) { something(); }
if (!0>0) { something(); }
if (!FALSE>0) { something(); }
if (TRUE>0) { something(); }
if (TRUE>FALSE) { something(); }
if (TRUE) { something(); }
Instead of what we might have initially expected
if (!count($items)>0) { something(); }
if (!0>0) { something(); }
if (!FALSE) { something(); }
if (TRUE) { something(); }
It’s always good to keep such things in mind while working in PHP, because seemingly innocent code can have very unexpected side effects. In this case it’s a bit harmless because the end result is the same, but sometimes this may not be the case.
As a good example of a less obvious deathtrap, please answer me the following question.
$items = '';
if (count($items)>0) { something(); }
Does “something();” get executed or not?