Short, Shorthand in PHP

Published 15th November 2010

Recently my knowledge of PHP has been developing and I’ve come across some shorthand code that at first glance looks wrong but is actually just obfuscated. How many times have you seen or done this in code:

if($something > 100){ $something_else = true; } else { $something_else = false; }

Ok so it’s long winded and boring so we shorten it. Usually it might become the following:

$something_else = false; if($something > 100) $something_else = true;

If your a real code ninja you might even know what a Ternary Operator is and get it all in one line:

$something_else = ($something > 100) ? true : false;

Now comes the short, shorthand (note this only works if you want $something_else to be a boolean). I actually found this when looking through the WordPress source code (Update: see Andrews comment). It’s the double exclamation operator and looks something like:

$something_else = !!$something;

What this does is to make sure that the returned value is always a boolean. So no matter what type $something is, the returned value will always be true or false (technically 1 or 0). So for example here is what it returns for a range of different types:

!! undef == 0 !! 0 == 0 !! 1 == 1 !! $obj == 1 !! 100 == 1

So there is an example of how short you can get your shorthand in PHP. Remember that using these techniques can be very confusing and are not recommended for portions of code that need to be easily understood.