Skip to content
Advertisement

Multiple if/then arguments in PHP for HTML classes

I would like to have an if/then argument for 2 classes (from the css) for a menu item. One where the menu item is blue if it is NOT the active page, and one where the menu item is red if it IS the active page. I have figured out the active page portion, now I am trying to figure out the if it is not active portion. I hope that makes sense. I have included a code snippit below.

<ul class="menu ul">
  <li><a class="Blue <?php if($page =='home'){echo 'active';}?>" href="../index.php" >Home</a></li>

I have tried multiple variations, however I cannot figure it out. Thanks for your help!

Advertisement

Answer

as far as I understood you want to add different classes to link depending on $page variable. for this i would recommend you to just use else statement

  <ul class="menu ul">
  <li><a class="<?php if($page =='home'){echo 'Blue';}else{echo 'Red';} ?>" href="../index.php" >Home</a></li>`

However it would be much better to check state of $page somewhere up (to not make spagetti code). And then echo only class in the a element.

 <?php if($page =='home'){$menu_class='Blue';}else{$menu_class= 'Red';};?>
 <ul class="menu ul">
  <li><a class="<?php echo $menu_class; ?>" href="../index.php" >Home</a></li></pre> 
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement