Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jul 2006
    Posts
    138
    Thanks
    3
    Thanked 0 Times in 0 Posts

    & and && difference

    Stupid question:

    In php what is the difference between

    Code:
    if(getName() & $level){
      return 1;
    }
    Code:
    if(getName() && $level){ // Notice the && here
      return 1;
    }
    Why does it return different answer?
    Thanks

  • #2
    Regular Coder
    Join Date
    Jul 2006
    Posts
    138
    Thanks
    3
    Thanked 0 Times in 0 Posts
    NVM Got it! Sorry

  • #3
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,978
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    Quote Originally Posted by neo_philiac View Post
    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:
    PHP Code:
    /*
    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 2// 0 = 0000 0001 & 0000 00010 (no corresponding bits)
    print 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:
    PHP Code:
    $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)
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •