PHP Ternary Operator

The ternary operator in PHP is a shorthand way of writing an if-else statement. It makes your code shorter and more readable.

🛠 Syntax of the Ternary Operator

The ternary operator uses three parts:

(condition) ? value_if_true : value_if_false;

It checks the condition. If it’s true, it returns the first value; otherwise, it returns the second value.

📝 Example 1: Basic Ternary Operator

Let’s check if a number is even or odd.

<?php
$number = 10;
$result = ($number % 2 == 0) ? "Even" : "Odd";
echo $result; // Output: Even
?>
    

Try It Now

📝 Example 2: Ternary Operator with User Input

Check if a user is old enough to vote.

<?php
$age = 18;
$message = ($age >= 18) ? "You can vote!" : "You cannot vote yet.";
echo $message;
?>
    

Try It Now

📝 Example 3: Nested Ternary Operator

Find the largest number among three.

<?php
$a = 10;
$b = 20;
$c = 15;
$max = ($a > $b) ? (($a > $c) ? $a : $c) : (($b > $c) ? $b : $c);
echo "Largest number is: " . $max; // Output: 20
?>
    

Try It Now

🎯 Why Use the Ternary Operator?

  • ✅ Makes code shorter and cleaner
  • ✅ Works great for simple if-else conditions
  • ✅ Improves readability in PHP scripts

📝 Practice Time!

Try modifying the examples above and see how the ternary operator works with different values. The best way to learn is by experimenting! 🚀