Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does & in &2 mean in PHP?

Tags:

php

In the last line of the following code, it has &2, if($page['special']&2).

What does & mean?

if(isset($_REQUEST['id']))$id=(int)$_REQUEST['id'];
else $id=0;
if($id){ // check that page exists
    $page=dbRow("SELECT * FROM pages WHERE id=$id");
    if($page!==false){
        $page_vars=json_decode($page['vars'],true);
        $edit=true;
    }
}
if(!isset($edit)){
    $parent=isset($_REQUEST['parent'])?(int)$_REQUEST['parent']:0;
    $special=0;
    if(isset($_REQUEST['hidden']))$special+=2;
    $page=array('parent'=>$parent,'type'=>'0','body'=>'','name'=>'','title'=>'','ord'=>0,'description'=>'','id'=>0,'keywords'=>'','special'=>$special,'template'=>'');
    $page_vars=array();
    $id=0;
    $edit=false;
}

// { if page is hidden from navigation, show a message saying that
if($page['special']&2)echo '<em>NOTE: this page is currently hidden from the front-end navigation. Use the "Advanced Options" to un-hide it.</em>';
like image 311
shin Avatar asked Jan 16 '11 12:01

shin


2 Answers

$page['special'] & 2

means

$page['special'] bitwise AND 2

It basically checks to see if the 2 bit is set in $page['special'].

This line:

if(isset($_REQUEST['hidden']))$special+=2;

explicitly adds 2 to $special so that it'll satisfy the bitwise AND operation and comparison, because decimal 2 == binary 10, with the 1 representing the 21 bit, ensuring it is set.

The AND operation returns 2 if the 2 bit is set, which resolves to true in PHP and satisfies the condition; otherwise it returns 0 which is considered false.

Quite a neat trick IMO, not sure how secure it is though.

like image 185
BoltClock Avatar answered Nov 19 '22 19:11

BoltClock


& is the bitwise AND operator. The result of a & b are the bits that are equal in a and b.

So in this case $page['special']&2 returns either 0 or 2 depending on the bit pattern of $page['special']:

  **** **** **** **** **** **** **** **X*    // $page['special']
& 0000 0000 0000 0000 0000 0000 0000 0010    // 2
=========================================
  0000 0000 0000 0000 0000 0000 0000 00X0    // $page['special'] & 2
like image 13
Gumbo Avatar answered Nov 19 '22 18:11

Gumbo