Such a condition:

<?php $age = '20'; if ($age>=15 && $age<=19) { echo "ะžะš"; } ?> 

Why in the case of && and if you change to & , it will not output anything? What is the difference between these operators?

But if

  • && - logical operator, & - bitwise - Alexey Shimansky
  • Both $age>=15 && $age<=19 and $age>=15 & $age<=19 in your example will return the same result (the difference is only in the type of value). Proof: ideone.com/crHmAj A question about anything! - Dmitriy Simushev

1 answer 1

&& is the logical "AND"

It works like this: C = A && B

 โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ A โ”‚ B โ”‚ C โ”‚ โ•žโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ก โ”‚ true โ”‚ true โ”‚ true โ”‚ โ”‚ true โ”‚ false โ”‚ false โ”‚ โ”‚ false โ”‚ true โ”‚ false โ”‚ โ”‚ false โ”‚ false โ”‚ false โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ 

& is a bitwise "and". It works like this:

C = A & B

  1. A and B are decomposed into a bit representation. Suppose A = 12, and B = 23, then (we count them as bytes)

     A=00001100 B=00010111 
  2. After that, a logical AND is applied to each pair of corresponding data bits A and B (see table above)

     A = 0 0 0 0 1 1 0 0 B = 0 0 0 1 0 1 1 1 C = 0 0 0 0 0 1 0 0 = 3 

Therefore, 12 & 23 = 3

Now, as for your case. PHP is a language with dynamic typing, hence all the "magic".

$age>=15 && $age<=19 - everything is clear, I hope? Returns true if $ age is between 15 and 19.

$age>=15 & $age<=19 . What happens here? It's simple, first two comparisons are performed, because y >= and <= priority is higher, these comparisons return boolean values: true and false. Then comes the & operator queue, but it does not work with a logical type, so first true=>1 and false=>0 converted, the bitwise ะ˜ is applied to these values โ€‹โ€‹and the result is converted back to a boolean value, 0 to false and 1 to true.