Table of Contents
PHP Logical Operators: Making Logical Decisions in PHP
The PHP logical operators are used to combine conditional statements.
| Operator | Name | Example | Result |
|---|---|---|---|
| and | And | $x and $y | True if both $x and $y are true |
| or | Or | $x or $y | True if either $x or $y is true |
| xor | Xor | $x xor $y | True if either $x or $y is true, but not both |
| && | And | $x && $y | True if both $x and $y are true |
| || | Or | $x || $y | True if either $x or $y is true |
| ! | Not | !$x | True if $x is not true |
Example: $x and $y
True if both $x and $y are true
Code:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 50;
$y = 60;
if ($x == 50 and $y == 60) {
echo "Happy Code!";
}
?>
</body>
</html>
Output:
This will produce the following result
Happy Code!
Example: $x or $y
True if either $x or $y is true
Code:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 60;
$y = 50;
if ($x == 60 or $y == 80) {
echo "Happy Code!";
}
?>
</body>
</html>
Output:
This will produce the following result
Happy Code!
Example: $x xor $y
True if either $x or $y is true, but not both
True if either $x or $y is true, but not both
Code:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 60;
$y = 50;
if ($x == 60 xor $y == 80) {
echo "Happy Code!";
}
?>
</body>
</html>
Output:
This will produce the following result
Happy Code!
Example: $x && $y
True if both $x and $y are true
Code:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 60;
$y = 50;
if ($x == 60 && $y == 50) {
echo "Happy Code!";
}
?>
</body>
</html>
Output:
This will produce the following result
Happy Code!
Example: $x || $y
True if either $x or $y is true
Code:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 60;
$y = 50;
if ($x == 60 || $y == 80) {
echo "Happy Code!";
}
?>
</body>
</html>
Output:
This will produce the following result
Happy Code!
Example: !$x
True if $x is not true
Code:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 70;
if ($x !== 90) {
echo "Happy Code!";
}
?>
</body>
</html>
Output:
This will produce the following result
Happy Code!