Master these pro tricks to write efficient PHP: Null coalescing (??), array destructuring, spaceship operator (<=>), short ternary (?:), and variadic functions (...). Save time, reduce clutter, and boost performance!

1. Null Coalescing Operator (??
)
Quickly assign defaults if a variable is unset or null:
$username = $_POST['name'] ?? 'Anonymous'; // No isset() needed!
2. Array Destructuring
Unpack arrays into variables in one line:
[$firstName, $lastName] = explode(' ', 'John Doe'); // $firstName = 'John', $lastName = 'Doe'
3. Spaceship Operator (<=>
)
Compare values easily (returns -1, 0, or 1
):
usort($users, fn($a, $b) => $a['age'] <=> $b['age']); // Sort users by age
4. Short Ternary (?:
)
Quick fallback for falsy values (but careful—unlike ??, it checks for falsy, not just null):
$status = $user->getStatus() ?: 'pending'; // If falsy (e.g., empty string, 0), use 'pending'
5. Variadic Functions (...
)
Accept unlimited arguments effortlessly:
function mergeStrings(...$strings) {
return implode(' ', $strings);
}
mergeStrings('Hello', 'world', '!'); // "Hello world !"
Why these?
- Spaceship operator simplifies sorting/comparisons.
- Short ternary is handy (but know its quirks vs
??
). - The rest remain clean, modern, and widely useful.
Good for PHP 7.0+! 🚀
Happy Coding! 😊