During today’s work I had a brief conversation on Twitter with some friends of mine on the topic of PHP methods, which is hardly the first or last time this is “discovered” and/or ranted about:
Foo: You have to love PHP: empty(“0″) === TRUE :D
Me: @Foo Or just RTFM… ;) http://php.net/manual/en/function.empty.php
Foo: @Me TFM doesn’t make it any less absurd/hateable :P
Bar: @Me I’m with @Foo common sense before manuals
Although I to some extend can agree with both this small chat got me thinking about the usage of common sense as the universal fallback or solution when things goes wrong, a concept that has pondered my mind from time to time. Even though it may be considered surprising, if not just plain stupid, that empty(“0″) returns false true (thanks for the correction ;)) it is actually clearly stated in the manual of the method. Which my friend could have seen if bothered to read it. The problem I see is that when people make assumptions based on their own mental model – their “common sense”- things occasionally go wrong when things don’t comply with (again, their) reality. But instead of relying on what you believe I claim that it is better to rely on facts than on an obviously broken concept that to begin with. There is a reason why we year 2011 still have traffic lights, warning labels on coffee mugs stating “Warning! This beverage is hot!”, and some people still believe in tooth fairies and whatnot.
For those new to PHP or who has discovered “weird” things in the language I also recommend keeping PHP type comparison tables and Type Juggling close by. Even though I’m tempted to just say “use your common sense“.
Dave Maven
thought 111 days ago:“Even though it may be considered surprising, if not just plain stupid, that empty(“0″) returns false it is actually clearly stated in the manual of the method.”
You mean, returns true, not returns false here, right?
I think I agree with the gist of your post — people often just use “common sense” when they can’t think of another reason. And then they act like somehow by issuing this invocation they are super smart.
Still, whether it should return true or false is the issue. That is an issue of the language design. Not a lot of other languages have gone PHP’s way, but I think this is because PHP was designed with form handling in mind, where it made sense in a lot of cases to “0″ as false. A lot of times the empty() function does exactly what I want, in other cases I want something like Rails’ “blank?” method.
Nicklas
thought 104 days ago:Heh, yeah you are right, thanks for the correction!
And yeah you are probably right on your 2nd comment as well. The language was created for doing one thing and one thing well: handling web requests. In that context the input is always strings and thus I suppose they took the path of trying to guess the most common use-case of input.