Skip to content
Advertisement

Syntax for multiple “or” statements to set a CSS class

I’m quite new to PHP. The problem statement is, I need to insert a CSS class into the nav on specific pages. Here’s the way I have it now:

<nav class="navbar navbar-expand-md navbar-light fixed-top scrolling-navbar 
<?php if (basename($_SERVER['PHP_SELF']) === 'index.php' || basename($_SERVER['PHP_SELF']) === 'shop.php'  || basename($_SERVER['PHP_SELF']) === 'news.php') { echo "navbar-transparent"; } ?>
">

It works but it feels messy. I’m going to continue to research it (perhaps a switch statement is better?). Is there a cleaner way of doing this?

Advertisement

Answer

If you want to check if a value is in a set, an easy option is to use the in_array function.

if(in_array(basename($_SERVER['PHP_SELF']), ['index.php', 'shop.php', 'news.php']))
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement