PHP Logical & Conditional Operators Explained with Examples
What Are PHP Logical and Conditional Operators?
In PHP, logical and conditional operators help make decisions in your programs.
They are used to combine multiple conditions or test whether a condition is true or false.
These operators return a Boolean value (true or false) and are mainly used inside if, while, and for statements to control program flow.
Let’s explore them step by step
Logical Operators
Logical operators are used to combine two or more conditions.
| Operator | Name | Description | Example |
|---|---|---|---|
&& or and | Logical AND | True if both conditions are true | $x && $y |
| ` | oror` | Logical OR | |
! | Logical NOT | Reverses the condition | !$x |
xor | Logical XOR | True if only one condition is true | $x xor $y |
AND (&& or and)
Returns true if both conditions are true.
Example:
<?php
$age = 22;
$citizen = true;
if ($age >= 18 && $citizen) {
echo "Eligible to vote";
}
?>
Output:
Eligible to vote Explanation:
Both conditions are true, so the result is true.
OR (|| or or)
Returns true if at least one condition is true.
Example:
<?php
$marks = 40;
if ($marks >= 35 || $marks == 34) {
echo "You passed!";
}
?>
Output:
You passed! Explanation:
Even if one condition ($marks >= 35) is false, the second ($marks == 34) makes the whole condition true.
NOT (!)
Reverses the result of a condition.
If true → becomes false, and vice versa.
Example:
<?php
$isHoliday = false;
if (!$isHoliday) {
echo "Go to work!";
}
?>
Output:
Go to work! Explanation:!false becomes true, so the message prints.
XOR (Exclusive OR)
Returns true only if one condition is true and the other is false.
Example:
<?php
$a = true;
$b = false;
if ($a xor $b) {
echo "Only one condition is true!";
}
?>
Output:
Only one condition is true! Explanation:
If both are true or both are false, result will be false.
Conditional (Ternary) Operator (?:)
The ternary operator is a shortcut for if-else statements.
It takes three parts:
(condition) ? value_if_true : value_if_falseExample:
<?php
$marks = 80;
$result = ($marks >= 50) ? "Pass" : "Fail";
echo $result;
?>
Output:
Pass Explanation:
Since $marks >= 50 is true, "Pass" is assigned to $result.
Real-World Example: Eligibility Check
<?php
$age = 19;
$citizen = true;
$status = ($age >= 18 && $citizen) ? "You can vote" : "Not eligible";
echo $status;
?>
Output:
You can vote Explanation:
Both conditions are true, so $status gets "You can vote".