PHP: Boolean Not or (int)!

Came across this little snippit today and I’ve never seen it before. My colleague, Ben Spencer, who is a bit of a wizard helped my addled brain understand it. I thought I’d create a small chunk of code to get my head round it as it’s quite useful.

        echo 'Length: '. 100 ."\n";
        // Prints: Length: 100
        echo 'Length(False): '. (100 - (int)! false) ."\n";
        // Prints: Length(False): 99
        echo 'Length(True): '. (100 - (int)! true) ."\n";
        // Prints: Length(True): 100
        echo 'Length(with int): '. (100 - (int)! 20) ."\n";
        // Prints: Length(with int): 100

Of course, the purists amongst you might rally against this, but I thought it was cool.

One thought on “PHP: Boolean Not or (int)!

  1. What this is doing is not obvious. I think we’re playing games with type coercion here:

    100 – 1 == 99
    100 – 0 == 100

    that’s simple.

    (int) converts the expression which follows into an integer



    so (int) !false==1


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s