Reading recently I found a few PHP expressions, operators, etc. that I wish I had known earlier. It’s not that you’re doing it wrong, it’s just that there are some faster options.
Examples
Ternary Operators
$age = 18; $example = $age >= 18 ? "Can vote" : "Can't vote"; $example = $age == 18 ? 'true' : 'false'; $example = ($age >= 18) ? "Can vote" : "Can't vote"; //can use parentheses
Switch Statements
$day = 'Thursday'; switch($day) { case 'Saturday': $hours = 'Open 9am-5pm'; break; case 'Sunday': $hours = 'Closed'; break; default: $hours = 'Open 9am-8pm'; }
Match Expressions
$day = 'Tuesday'; $hours = match($day) { //match was added to and requires PHP 8 'Saturday' => 'Open 9am-5pm'; 'Sunday' => 'Closed'; 'Monday', 'Tuesday' => 'Extended hours. Open 9am-10pm'; default => 'Open 9am-8pm'; }
Echo Shorthand
<p>Store Hours: <?= $hours ?></p>
Conclusion
There are at least a few projects where I could have used these. How about you? Have could you have used these or have you come across any that you wish you knew earlier?