0
0
PHPprogramming~5 mins

Ternary operator in PHP

Choose your learning style9 modes available
Introduction

The ternary operator helps you choose between two values quickly in one line. It makes your code shorter and easier to read.

When you want to set a variable based on a simple condition.
When you want to print one message if something is true, and another if it is false.
When you want to return a value from a function depending on a condition.
When you want to avoid writing a full if-else block for a quick choice.
Syntax
PHP
$result = (condition) ? value_if_true : value_if_false;

The condition is checked first.

If the condition is true, the value after the question mark (?) is used.

If the condition is false, the value after the colon (:) is used.

Examples
This sets $status to 'Adult' if $age is 18 or more, otherwise 'Minor'.
PHP
$age = 20;
$status = ($age >= 18) ? 'Adult' : 'Minor';
echo $status;
This prints 'Pass' if the score is 60 or more, else 'Fail'.
PHP
$score = 75;
$message = ($score >= 60) ? 'Pass' : 'Fail';
echo $message;
This prints a welcome message if logged in, otherwise asks to log in.
PHP
$is_logged_in = false;
echo $is_logged_in ? 'Welcome back!' : 'Please log in.';
Sample Program

This program checks if the temperature is above 25. If yes, it says 'Hot', otherwise 'Cold'.

PHP
<?php
$temperature = 30;
$weather = ($temperature > 25) ? 'Hot' : 'Cold';
echo "The weather is $weather.";
?>
OutputSuccess
Important Notes

You can nest ternary operators but it can make code hard to read.

Use parentheses to make complex conditions clear.

Summary

The ternary operator is a short way to choose between two values.

It uses the format: condition ? value_if_true : value_if_false.

It helps keep code simple and clean for quick decisions.