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.


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';
   case 'Sunday':
      $hours = 'Closed';
      $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>


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?

Article Categories:

Web developer, designer and all around tech lover. Christoph started sdatic.com as a way to organize his ideas, research and notes as well as share resources with his fellow tech friends. Everything you see here is a resource that he will use or found while running his company MicroMacro Technology based in the Denver area.

Leave a Reply

Your email address will not be published. Required fields are marked *