Replace verbose ternary checks and null coalescing reassignments with PHP null coalescing assignment operator (??=).
Setting default values on nullable variables often leads to repetitive variable references across statements.
PHP supports null coalescing assignment (??=) to combine evaluation and assignment into a single expression:
$username = null;
// Verbose ternary operator
$username = $username !== null ? $username : 'MrPunyapal';
// Null coalescing operator
$username = $username ?? 'MrPunyapal';
// Clean null coalescing assignment
$username ??= 'MrPunyapal';
- Only assigns the right-hand value if the left-hand variable is
null - Prevents repeating variable names on both sides of the assignment
- Reduces code clutter in configuration arrays and option initialization
Related Tips
View all tips →Match Multiple Values in a Single Match Arm in PHP
Separate multiple comma-delimited values within a single match expression arm to group identical execution branches.
Simplify Class Instantiation with Constructor Property Promotion
Combine property declarations and constructor parameter assignments in PHP 8 for concise class definitions.