1

I was reviewing some PHP code and found a block of conditional statements that I couldn't understand .

     if ($options['mentionbbcode'] & 8) {
                $final_rendered .= '<span class="highlight">';
        } 
     if ($options['mentionbbcode'] & 4) {
                $final_rendered .= '<i>';
        } 

     if ($options['mentionbbcode'] & 2) {
                $final_rendered .= '<b>';
        }

what is the difference between those three conditionals .. shouldn't they all return true if $options['mentionbbcode'] is set ? what is the role of the integer value here ?

Kamal Saleh
  • 479
  • 1
  • 5
  • 20
  • 1
    Have a look at [bitwise operators](http://php.net/manual/en/language.operators.bitwise.php). – Jonnix Aug 07 '17 at 08:22
  • Thanks for the response , could you give me example where this statement return true and another where it will return false ? – Kamal Saleh Aug 07 '17 at 08:27

1 Answers1

1

That is a bitwise and operation.

So for example when using $value = $var & 8, $value will be a number for which the bits that are 1 in both $var and 8 are also 1 in the new value.

In your case, these conditions are testing if a certain bit is set for the value, the 4th, 3rd and 2nd to be correct.

Update:
Here are some examples of results with different values for the first condition. It tests if the fourth bit from the right is set.

12 & 8 // true  (01010 & 01000 => 01000)
15 & 8 // true  (01111 & 01000 => 01000) 
7  & 8 // false (00111 & 01000 => 00000)
17 & 8 // false (10001 & 01000 => 00000)

As long as one bit in a number is set, PHP will interpret this as true.

Jerodev
  • 32,252
  • 11
  • 87
  • 108