PHP Logical Operators

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. 😞";
    }
?>
    

Try It Now

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. 😞";
    }
?>
    

Try It Now

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! πŸ’€";
    }
?>
    

Try It Now

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! πŸ˜…";
    }
?>
    

Try It Now

🎯 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!