Search code examples
phphtmlmenu

Setting an active class on a menu item with PHP


I have a simple menu made of <ul><li> elements and a class="active" in place to mark the current page. A variable is passed by $_get[] to select the specific page by url: ?pg=PAGE.

I am fairly new to php and still learning. This works just fine, but i feel there ought to be a simpler and shorter way.

<ul class="nav">
  <li <?php if ($_GET['pg'] == "PAGE1") { echo "class=\"active\""; } ?>><a href="?pg=PAGE1">FIRST PAGE</a></li>
  <li <?php if ($_GET['pg'] == "PAGE2") { echo "class=\"active\""; } ?>><a href="?pg=PAGE2">SECOND PAGE</a></li>
</ul>

Solution

  • <?php
        $pages = array(
            'PAGE1' => 'FIRST PAGE',
            'PAGE2' => 'SECOND PAGE');
    ?>
    
    <ul class="nav">
      <?php foreach ($pages as $pageId => $pageTitle): ?>
      <li <?=(($_GET['pg'] == $pageId) ? 'class="active"' : '')?>><a href="?pg=<?=$pageId?>"><?=$pageTitle?></a></li>
      <?php endforeach; ?>
    </ul>
    

    http://php.net/manual/en/control-structures.foreach.php

    Don't repeat yourself -- both li-s are very similar, the only difference is in page ID and title. This approach will really help once you have more than two pages.

    Try to keep PHP and HTML as separate as possible -- this will make your life easier once you decide to keep them in separate files (and you will sometimes).