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();
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();
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):
1 (it's 0001) and 5 (it's 0101).AND (from right to left):
true)false)false)false)So the result is 0001 (binary representation of 1).