0
0
PhpConceptBeginner · 3 min read

What is Ternary Operator in PHP: Simple Explanation and Example

The ternary operator in PHP is a shorthand way to write an if-else statement in a single line. It uses the syntax condition ? value_if_true : value_if_false to choose between two values based on a condition.
⚙️

How It Works

The ternary operator in PHP works like a quick decision maker. Imagine you are choosing between two snacks based on whether you are hungry or not. Instead of writing a long explanation, you just say: "If hungry, eat an apple; otherwise, eat a cookie." The ternary operator does the same for your code.

It checks a condition first. If the condition is true, it returns the first value after the question mark ?. If the condition is false, it returns the second value after the colon :. This lets you write simple choices in one line instead of multiple lines with if and else.

💻

Example

This example shows how to use the ternary operator to check if a number is even or odd and print a message accordingly.

php
<?php
$number = 7;
$message = ($number % 2 === 0) ? 'Even number' : 'Odd number';
echo $message;
?>
Output
Odd number
🎯

When to Use

Use the ternary operator when you need to choose between two simple values based on a condition. It makes your code shorter and easier to read for quick decisions.

For example, you can use it to set default values, display messages, or assign variables without writing full if-else blocks. However, avoid using it for complex logic because it can become hard to understand.

Key Points

  • The ternary operator is a shortcut for if-else statements.
  • It uses the syntax: condition ? value_if_true : value_if_false.
  • It helps write concise and readable code for simple choices.
  • Avoid using it for complex or nested conditions to keep code clear.

Key Takeaways

The ternary operator simplifies if-else statements into one line.
Use it to quickly choose between two values based on a condition.
It improves code readability for simple decisions.
Avoid complex or nested ternary operators to keep code clear.