PHP Logical Operators

PHP has three logical operators:

  1. And operator (&& or and): The and operator returns true if both operands are true. For example:
$var1 = true;
$var2 = false;
if ($var1 && $var2) {
   echo "This won't be printed because both variables are not true.";
}
  1. Or operator (|| or or): The or operator returns true if at least one of the operands is true. For example:
$var1 = true;
$var2 = false;
if ($var1 || $var2) {
   echo "This will be printed because at least one of the variables is true.";
}
  1. Not operator (!): The not operator returns the opposite of the operand. For example:
 
$var1 = true;
if (!$var1) {
   echo "This won't be printed because the variable is true.";
}

It’s important to note that the logical operators in PHP use short-circuit evaluation. This means that if the first operand of an and operation is false, the second operand is not evaluated. Similarly, if the first operand of an or operation is true, the second operand is not evaluated. This can be used to optimize code and avoid unnecessary computations.

PHP Logical Operator are and or not

ExampleNameResult
$a and $bAndTRUE if both $a and $b are TRUE.
$a or $bOrTRUE if either $a or $b is TRUE.
$a xor $bXorTRUE if either $a or $b is TRUE, but not both.
! $aNotTRUE if $a is not TRUE.
$a && $bAndTRUE if both $a and $b are TRUE.
$a || $bOrTRUE if either $a or $b is TRUE.

Example for PHP Logical Operators

<?php
$a = true;
$b = false;

if($a && $b) {
echo ‘Both $a and $b are true. <br />’;
}
// Print the statement if $foo OR $bar is true
if($a || $b) {
echo ‘At least one of the variables is true. <br />’;
}
// Print the statement if $foo OR $bar is true, but not both
if($a xor $b) {
echo ‘One variable is true, and one is false. <br />’;
}
// Print the statement if $bar is NOT true
if(!$b) {
echo ‘$b is false. <br />’;
}
?>