PHP Logical Operators

In this lesson, you will learn about Logical Operators in PHP, their usage, and examples to better understand the topic.


PHP Logical Operators

Logical operators in PHP are used to combine logical statements, such as a & b or a | b. The table below illustrates the different Logical Operators in PHP.

Logical Operators Symbol Logical Operators’ Names Example
And And $a and $b
Or Or $a or $b
Xor Xor $a xor $b
&& And $a && $b
|| Or $a || $b
! Not !a

Example

<?PHP
echo "PHP Logical Operator Example";
echo "<br>";
echo "  ---------------------------------------- ";
echo "<br>";
$a = 24;
$b = 12;
echo '$a  = 24';
echo "<br>";
echo '$b  = 12';
echo "<br>";
$Yes = 'Congratulations !! ';
$No = 'Oops!! ';
//and operator checks if two operands are equal, then condition turns true.
if ($a and $b)
{
    echo $Yes, $a, " and ", $b, " Both operands are true ";
}
else
{
    echo $No, $a, " and ", $b, " Either operands is not true ";
}
echo "<br>";
//&& operator checks if two operands are equal, then condition turns true.
if ($a && $b)
{
    echo $Yes, $a, ' && ', $b, " Both operands are true ";
}
else
{
    echo $No, $a, ' && ', $b, " Either operands is not true ";
}
echo "<br>";
//|| operator checks if either operands is true, then condition turns true.
if ($a || $b)
{
    echo $Yes, $a, ' || ', $b, " Either operands is true ";
}
else
{
    echo $No, $a, ' || ', $b, " Both operands are false ";
}
echo "<br>";
//or operator checks if either operands is true, then condition turns true.
if ($a or $b)
{
    echo $Yes, $a, " or ", $b, " Either operands is true ";
}
else
{
    echo $No, $a, " or ", $b, " Both operands are false ";
}
echo "<br>";
if ($a)
{
    echo $Yes, $a, " operand is true ";
}
else
{
    echo $No, $a, " operand is not true ";
}
echo "<br>";
if (!$a)
{
    echo $Yes, $a, " operand is true ";
}
else
{
    echo $No, $a, " operand is not true ";
}
?>

Output

PHP Logical Operator Example
---------------------------------------- 
$a = 24
$b = 12
Congratulations !! 24 and 12 Both operands are true 
Congratulations !! 24 && 12 Both operands are true 
Congratulations !! 24 || 12 Either operands is true 
Congratulations !! 24 or 12 Either operands is true 
Congratulations !! 24 operand is true 
Oops!! 24 operand is not true

This concludes the PHP Logical Operators lesson. In the next lesson, I will teach you another type of operator in PHP, Assignment Operators.