SoFunction
Updated on 2025-04-06

Guide to getting out of php and && in php

I originally thought that and and in PHP are the same, but the writing is for readability and aesthetics. In fact, I was wrong. There is a pit hidden in it!
Look at the following code:

$bA = true;
$bB = false;
$b1 = $bA and $bB;
$b2 = $bA && $bB;
var_dump($b1); // $b1 = true
var_dump($b2); // $b2 = false
$bA = false;
$bB = true;
$b3 = $bA or $bB;
$b4 = $bA || $bB;
var_dump($b3); // $b3 = false
var_dump($b4); // $b4 = true

Strange, and the results of and/&& and or/|| are different. What is the problem?
Let's look at another piece of code!

$bA = true;
$bB = false;
var_dump($bA and $bB); // false
var_dump($bA && $bB); // false
$bA = false;
$bB = true;
var_dump($bA or $bB); // true
var_dump($bA || $bB); // true

Even more strange, why is it right at this time. So the question may appear on =, after a while, Google and documentation, I finally found the answer!

Operator priority

Through this table, we can see that the priority of the two sets of operators and/&& and or/|| is actually different. The priority of and or and or is lower than =, so the above code is easy to understand, which is to do assignment first and then do a logical operation of and or or, and the result of this operation has not survived. So the result that comes out finally makes us incredible.

Bonding Operators Additional Information
No binding clone new Clone and new
Left [ Array
Left ** arithmetic
right ++ — ~ (int) (float) (string) (array) (object) (bool) @ Type and self-increase/self-decrease
No binding instanceof type
right ! Logical operations
Left * / % arithmetic
Left + – . Arithmetic and strings
Left << >> Bitwise operation
No binding < <= > >= Comparative operations
No binding == != === !== <> Comparative operations
Left & Bitwise operations and references
Left ^ Bitwise operation
Left | Bitwise operation
Left && Logical operations
Left | | Logical operations
Left ?: Three-way condition selection
right = += -= *= /= .= %= &= = ^= <<= >>= => | Assignment
Left and Logical operations
Left xor Logical operations
Left or Logical operations
Left , Many use