Ternary Operator

A compact one-line shorthand for an if/else statement.

Syntax$result = condition ? valueIfTrue : valueIfFalse;

The ternary operator is a shortcut for a simple if/else. It evaluates a condition and returns one of two values.

PHP also has the short ternary ?:, which returns the first value if it is truthy.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Inline a stock-status label — 'In Stock' or 'Sold Out' — based on a quantity variable in a product listing.
  • Assign a CSS class name for 'active' or 'inactive' in a template without a full if-else block.
  • Set a default greeting to 'Guest' when a logged-in user's name is absent.

More examples

Basic ternary expression

The ternary evaluates a condition and returns the first value when true, the second when false.

Example · php
<?php
$stock = 3;
$label = $stock > 0 ? 'In Stock' : 'Sold Out';

echo $label; // In Stock

Ternary inside a string

Wrapping a ternary in parentheses lets you inline it inside string concatenation for template-building.

Example · php
<?php
$isAdmin = true;
$nav = '<a href="/' . ($isAdmin ? 'admin' : 'dashboard') . '">Go</a>';

echo $nav; // <a href="/admin">Go</a>

Short ternary (Elvis operator)

The short ternary ?: returns the left side if it is truthy, otherwise the right side — a compact non-empty fallback.

Example · php
<?php
$name = $_GET['name'] ?? '';
$display = $name ?: 'Guest';

echo "Hello, $display!";

Discussion

  • Be the first to comment on this lesson.