480-747-3060

Home » Technology Topics » Doublebang

Doublebang

Ever seen or written this PHP code?

function foo( $foo ) {
    // magic
    if ( $foo ) // $foo is not bool
        return true;
    else
        return false;
}

So you want to return a boolean value (true/false) but $foo isn’t a bool so you can’t return it directly.

Option 1, cast to boolean:

function foo( $foo ) {
    // magic
    return (boolean) $foo;
}

Option 2, cast to “bool” (shortcut):

function foo( $foo ) {
    // magic
    return (bool) $foo;
}

Option3, doublebang:

function foo( $foo ) {
    // magic
   return !!$foo;
}

The first ! (the “not” operator) casts $foo to a negative bool, and the second one flips it back to the bool representation of its original value.

And of course if you want to return true when the variable evaluates as false, you can just do:

function foo( $foo ) {
    // magic
    return !$foo;
}

Appologies to anyone who has read this far and was expecting pornography.

Leave a Reply

Your email address will not be published. Required fields are marked *