PHP Shorthand Syntax

From Free Knowledge Base- The DUCK Project
Revision as of 07:31, 29 October 2025 by Littleguy (talk | contribs)
Jump to navigation Jump to search

Explaining shorthand such as null coalescing ??, short array syntax [], Elvis operator ?:, spaceship <=>, short echo <?= , arrow functions fn(), and assignment shorthands like +=)

the ternary operator (? :)

shorthand that has an if-else into one line, instead of explicit keywords like if, then, and else.

example:

echo $today_day === $tenant['rent_due_day'] ? 'DUE TODAY' : 'DELINQUENT';

is the same as:

if ($today_day === $tenant['rent_due_day']) {
    echo 'DUE TODAY';
} else {
    echo 'DELINQUENT';
}

Explicit words: if and else spell out the decision-making flow, like "If this is true, do X; otherwise, do Y." The ternary's ? (for "then") and : (for "else") are handy shortcuts, but they can blend into the condition.