Ternary ?: and the Short Ternary

The full a ? b : c and the short a ?: b. When to use each, and why nested ternaries need parentheses in PHP 8.

The ternary is your one-line if/else for producing a value. The short ternary ?: drops the middle: $x ?: $y returns $x when it's truthy, otherwise $y.

?: versus ??

They look similar but test different things. ?: checks truthiness (so 0 and "" fall through), while ?? checks only for null. Pick ?: for "if this is empty/falsy", ?? for "if this is missing".

<?php
$name = '';
echo $name ?: 'Guest';  // Guest  (empty string is falsy)
echo $name ?? 'Guest';  // ''     (empty string is not null)

Since PHP 8, nesting ternaries without parentheses is a fatal error — a deliberate guard against unreadable code.

Example

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

When to use it

  • Inline a badge label ('Active' or 'Inactive') in an HTML template without a full if block.
  • Use the short ternary ?: to provide a non-empty fallback for an optional form field.
  • Wrap a nested ternary in parentheses to make precedence explicit and avoid PHP 8 deprecation errors.

More examples

Full ternary in a template

The full a ? b : c ternary is concise for simple two-way choices inside template strings.

Example · php
<?php
$stock = 0;
$badge = $stock > 0 ? 'In Stock' : 'Sold Out';
$class = $stock > 0 ? 'badge-green' : 'badge-red';

echo "<span class=\"$class\">$badge</span>";

Short ternary (Elvis) for defaults

?: returns the left side when truthy, otherwise the right — shorter than a full ternary for non-empty defaults.

Example · php
<?php
$name    = $_POST['name'] ?? '';
$display = $name ?: 'Anonymous';

echo "Hello, $display!";

Parenthesised nested ternary

PHP 8 deprecates unparenthesised nested ternaries; always wrap the inner ternary to make precedence explicit.

Example · php
<?php
$score = 72;

// PHP 8 requires parentheses for nested ternaries
$grade = ($score >= 90)
    ? 'A'
    : (($score >= 75) ? 'B' : 'C');

echo $grade; // C

Discussion

  • Be the first to comment on this lesson.