• tutorials
  • php
  • using-switch-in-place-of-a-long-if-conditional-expression

Elegantly Using Switch in Place of a Long IF Conditional Expression

When you have a need to check for multiple possible values in a single variable, often the switch conditional is a preferred alternative to a long if ((...) || (...) || (...) ...) conditional expression.

Let's say, you want to display an advertising banner only on a number of certain pages:

index.php
switch ($page_name) { case 'about-us.php': case 'contact-us.php': case 'reviews.php': case 'index.php': ?> <div class="ad"> <figure> <a href="featured-products.php"> <img src="images/ad-banner.jpg" alt="a photo demonstrating our featured products"></a> </figure> </div> <?php break; } // end of SWITCH.

Apart from a more elegant code, another benefit of this design is that each possible case can be removed, or a new one added without breaking the PHP syntax, as there are no opening and closing parenthesis and logical OR, ||.

On the other hand when using IF, for that case, you'd need to go more carefully about editing its conditional expression:

if ( ($page_name === 'about-us.php') // Removing this line will result in a parse error! || ($page_name === 'contact-us.php') || ($page_name === 'reviews.php') || ($page_name === 'index.php') ) { // ...Display Advertisement... }
Elegantly Using Switch in Place of a Long IF Conditional Expression
This page was last updated on February 25, 2021
No comments have been posted so far
Leave a Comment