Search code examples
phparraysif-statementself

PHP condition, if current page, then link is highlighted


I have a webpage with a side bar that uses some css class. If the class = "active', then the link will be highlighted. I want to make it so that at any page, the script would check which link it's at, then decide which link to be highlighted. Below is where I'm at, but I really don't have a clue how to proceed, please point me in the right and better direction! If I have 20 links, this script would be way too long.... Thank you!


<?php






$arr = array(

'1' => '/about.php', 
'2'=> '/abt-history2.php',
'3' => '/abt-shop.php',
);

$host =  $_SERVER['REQUEST_URI'];


if($host == $arr['1']) 
{
    $class1 = "active";
}

else if ($host == $arr['2']) 
{
    $class2 = "active";
}

else if ($host == $arr['3']) 
{
    $class3 = "active";
}


 ?>






   <ul id="navigationSide">
      <div style="padding-left:20px; padding-bottom:10px; font-size:16px; font-weight:800; color:#777;">TITLE</div>
      <li><a href="<?php print $arr['1'];  ?>" class="<?php echo"$class1" ?>">AA</a></li>
      <li><a href="<?php print $arr['2'];  ?>" class="<?php echo"$class2" ?>">BB</a></li>
    </ul>
    <div style="padding:5px;"></div>
    <ul id="navigationSide">
      <div style="padding-left:20px; padding-bottom:10px;  font-size:16px; font-weight:800; color:#777;">TITLE2</div>
      <li><a href="<?php print $arr['3'];  ?>" class="<?php echo"$class3" ?>" >CC</a></li>

</ul>

Solution

  • Ok, this is new, I removed all I had posted before, and this is what another answer. Since, $_SERVER['REQUEST_URI'] gets /Portal/TEST/file.php in my localhost, I have added /Portal/TEST/ in the script, you can remove it depending on the structure of your files.

    <?php 
    $arr = array(
    
    '0' => '/Portal/TEST/about.php', 
    '1'=> '/Portal/TEST/abt-history2.php',
    '2' => '/Portal/TEST/abt-shop.php',
    '3' => '/Portal/TEST/extra.php',
    '3' => '/Portal/TEST/blaze.php',
    );
    
    
    
    
     ?>
    
    
    <h2>TITLE</h2>
    
    <?php 
    
     for($i=0; $i< count($arr); $i++) {  
    
    
    
        if($_SERVER['REQUEST_URI'] == $arr[$i]) {
    
        $class = 'active';
     ?>
    
    
      <li><a href="<?php print $arr[$i];  ?>" class="<?php echo "$class".$i ?>"><?php echo $class ?>
    </a></li>   <?php }else {
    $class  = 'In active';
    
    ?>  
      <li><a href="<?php print $arr[$i];  ?>" class="<?php echo "$class".$i ?>"><?php echo $class ?>
    </a></li> 
    
    <?php
    }
    
     }?>