PHP Shorthand Syntax
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 +=)
- PHP Compact Operators & Shorthands
- PHP Idiomatic Shorthands
- PHP One-Liners & Shorthands
PHP shorthand syntax
- Ternary Operator (? :): Shorthand for if-else statements.
- Null Coalescing Operator (??): Returns the first non-null value from a chain.
- Elvis Operator (?:): Shorthand for value ?: default (if value is truthy).
- Spaceship Operator (<=>): Compares two values, returning -1, 0, or 1.
- Short Array Syntax ([]): Alternative to array() for defining arrays.
- Short Echo Tag (<?=): Concise way to output expressions in templates.
- Arrow Functions (fn()): Compact anonymous functions for simple closures.
- Increment/Decrement (++, --): Pre/post shorthand for adding/subtracting 1.
- Assignment Shorthands (+=, -=, etc.): Combined assignment and operation.
- Shortened Boolean Conversion (!!): Explicitly converts to boolean true/false.
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.