Avi Nash
Avi Nash

Reputation: 37

Unable to understand "&" in this code. I am very beginner to php. Kindly let me know could any one solve it?

Unable to understand &in this code. I am very beginner to php. Kindly let me know could any one solve it?

  $a = 1;
  $b = &$a;
  $a =5&$b; 
  echo $a; 
  exit();

Upvotes: 1

Views: 86

Answers (1)

Marc
Marc

Reputation: 3709

In this context, the & is a bitwise and (bitwise operators).

$a = 1;     // the var a is now 1
$b = &$a;   // the var b is now the var a (not the int 1)
$a =5&$b;   // 5 & $b ( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101)
echo $a;    // prints 1
exit();

What this will do is getting the bit value of the numbers (1 = 0001 and 5 = 0101) and apply an and operation.

Some examples to understand other values in this context:

( 1 = 0001) = ( 1 = 0001) & ( 1 = 0001)
( 0 = 0000) = ( 1 = 0001) & ( 2 = 0010)
( 1 = 0001) = ( 1 = 0001) & ( 3 = 0011)
( 0 = 0000) = ( 1 = 0001) & ( 4 = 0100)
( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101)

Update: as OP asked, I will try to explain further:

A bitwise AND operator will take two equal-length binary representations and perform a logical AND.

A logical AND will take two operands and is true if and only if all of its operands are true.

So e.g.:

operand 1    operand 2    result
true         true         true
false        true         false
true         false        false
false        false        false

Note that true = 1 and false = 0.

So to explain what it's gonna do in your explicit case (1 & 5):

  • Get the binary representations of 1 (it's 0001) and 5 (it's 0101).
  • Perform a logical AND (from right to left):
    • 1 & 1 = 1 (true)
    • 1 & 0 = 0 (false)
    • 0 & 1 = 0 (false)
    • 0 & 0 = 0 (false)

So the result is 0001 (binary representation of 1).

Upvotes: 4

Related Questions