neo_philiac
08-25-2009, 09:37 PM
Stupid question:
In php what is the difference between
if(getName() & $level){
return 1;
}
if(getName() && $level){ // Notice the && here
return 1;
}
Why does it return different answer?
Thanks
Fou-Lu
08-26-2009, 08:09 AM
NVM Got it! Sorry :)
Glad to hear, I'll add in the solution in case anybody searches and gets this thread.
There is two purposes of the & operator. The first is for bitwise AND.
I'll demonstrate with byte values since I'm too lazy to put all of the 0's in there:
/*
1 = 0000 0001
2 = 0000 0010
3 = 0000 0011
Using the & sets all bits to 0 except where 1 exists in both the lhs and rhs of the operator
*/
print 1 & 2; // 0 = 0000 0001 & 0000 00010 (no corresponding bits)
print 3 & 2; // 2 = 0000 0010 & 0000 00011 (1 corresponding bits located at ^2)
The other use of the & opererator is the addressof operator. PHP doesn't actually use direct references and pointers, but its much easier to describe in this fashion:
$a = 1;
$b = &$a;
printf("\$a = %d, \$b = %d\n", $a, $b); // $a = 1, $b = 1
$a = 4;
printf("\$a = %d, \$b = %d\n", $a, $b); // $a = 4, $b = 4
Using the addressof operator indicates that $b will use the same memory location as $a for its variable storage. Any changes to this memory location will alter the referenced values.
Of course the && is for logical comparisons - FALSE && TRUE (false), TRUE && TRUE (true)