Ever wondered how you can check multiple conditions at once? Thatβs where Logical Operators come in! They help make smart decisions in your code by combining multiple conditions.
π What Are Logical Operators?
Logical operators allow you to combine multiple conditions and return either true
or false
.
Operator | Name | Description | Example |
---|---|---|---|
&& or and |
AND | Returns true if both conditions are true. |
$a && $b |
|| or or |
OR | Returns true if at least one condition is true. |
$a || $b |
! |
NOT | Reverses the condition. | !$a |
xor |
Exclusive OR (XOR) | Returns true if only one condition is true. |
$a xor $b |
1οΈβ£ AND Operator (&&) β All Must Be True β
Both conditions must be true
for the result to be true
. If one is false
, the whole thing is false
!
<?php $age = 25; $hasDrivingLicense = true; if ($age >= 18 && $hasDrivingLicense) { echo "You can drive! π"; } else { echo "Sorry, you can't drive yet. π"; } ?>
2οΈβ£ OR Operator (||) β At Least One Must Be True π―
If one condition is true
, the result is true
! Only false
if both are false
.
<?php $hasCoupon = true; $isVIP = false; if ($hasCoupon || $isVIP) { echo "You get a discount! π"; } else { echo "Sorry, no discount today. π"; } ?>
3οΈβ£ NOT Operator (!) β Flip It! π
Turns true
into false
and false
into true
! Think of it as a “reverse switch”.
<?php $isSleeping = false; if (!$isSleeping) { echo "Time to get some rest! π΄"; } else { echo "You're already sleeping! π€"; } ?>
4οΈβ£ XOR Operator (Exclusive OR) β Only One Can Be True π§
Returns true
if only one condition is true
. If both are true
or both are false
, it returns false
.
<?php $hasCar = true; $hasBike = true; if ($hasCar xor $hasBike) { echo "You have only one ride! ππ²"; } else { echo "Either you have both or none! π "; } ?>
π― Recap β Logical Operators in Action
- AND (&&) β All conditions must be true.
- OR (||) β At least one condition must be true.
- NOT (!) β Reverses the condition.
- XOR β Only one condition must be true.
π Practice Makes Perfect!
Try modifying the examples above and test different values. The more you practice, the better you’ll understand!