194
Views

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?

Article Categories:
Coding
SDATIC

Web developer and former photographer by trade...gamer and all around tech enthusiast in his free time. Christoph started sdatic.com as a way to organize his ideas, research, notes and interests. He also found it enjoyable to connect and share with others who parallel his interests. Everything you see here is a resource that he found useful or interesting and he hopes that you will too.

Leave a Reply

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