Tiago Serrano Tiago Serrano - 2 months ago 20
PHP Question

Highlight current value in loop menu

i'm trying to highlight current value in this loop menu:

<?php
for ($i=count($anos)-1;$i>=0;$i--)
echo '<li><a href="obra.php?ano='.$anos[$i]['ano'].'" onclick="window.location=\'obra.php?ano='.$anos[$i]['ano'].'\';">'.$anos[$i]['ano'].'</a></li>';
?>


I'm trying to fix some problems in a web page but my knowledge in programming is rudimentary at best. I've managed to fix a lot of issues by googling, but i'm having trouble getting a solution to this.

This loop gets the years (anos) from the DB and displays all of them in a menu, clicking on a year brings a page with the image gallery.

This is the page: http://marialealdacosta.com/obra.php

Thanks for the help.

Answer

You can use $_GET to use the passed value along with URL. In your case it's ano.

Use this value to compare with loop's value and if they are similar change the style of the element.

So your code look something like this,

<?php
     $ano="";
     if(array_key_exists("ano",$_GET)) { 
          /*
          Check if ano value is passed along with URL 
          before accessing it. Other wise it will give error.
          */

          $ano=$_GET["ano"];
     }
     for ($i=count($anos)-1;$i>=0;$i--) {
         $styles="";
         if($anos[$i]['ano']==$ano) { // this will check the current ano.
              $styles="background:red;"; // change appropriate styles here...
         }
         echo '<li style="'.$styles.'"><a href="obra.php?ano='.$anos[$i]['ano'].'" onclick="window.location=\'obra.php?ano='.$anos[$i]['ano'].'\';">'.$anos[$i]['ano'].'</a></li>';
    }

$_GET is an associative reserved array of variables passed to the current script via the URL parameters.

Comments