Skip to content

PHP Ternary Operator

Syntax

The ternary operator in PHP is a shorthand for if-else statements. It uses the syntax condition ? value_if_true : value_if_false.

<?php
// Assign a value based on a condition
$result = $condition ? $value_if_true : $value_if_false;
?>

Example

<?php
$age = 18;
// Check if user is an adult
$message = $age >= 18 ? "You are eligible to vote." : "You are not eligible to vote.";
echo $message;
// Output: You are eligible to vote.