Search code examples
phpif-statementampersand

What does a single ampersand mean in a PHP conditional statement?


The following code uses a single & in a conditional check. What does the single ampersand mean there?

if( $some_array_or_other_var & SOME_CONSTANT_VARIABLE ){ 
    //do something here 
}

It does not look like a reference, that's what confuses me.


Solution

  • That is a bitwise AND operation: http://www.php.net/manual/en/language.operators.bitwise.php

    If, after the bitwise AND, the result is "truthy", the clause will be satisfied.

    For example:

    3 & 2 == 2 // because, in base 2, 3 is 011 and 2 is 010
    4 & 1 == 0 // because, in base 2, 4 is 100 and 1 is 001
    

    This is commonly used to check a single bit in a bitset, by testing powers of two, you are actually checking if a specific bit is set.