Add active class to menu with PHP easily

Posted by: Alex on May 25, 2014

Making it evident which page the user is on in relation to the menu is a very common technique, however, there are lots of convoluted ways of doing it, many of which are manual, or require javascript.

The below script is the simplest way and my personal favourite for small – medium sized websites.

You simply define your menu in the $nav variable, and the following PHP automatically sees if the current page matches the link, if so it adds class="active" to the a link.

Using the class of active you can then style that link differently, making it clear the user is currently on that page.

$nav = <<<NAV
  <li><a href="/">Home</a></li>
  <li><a href="/about">About Us</a></li>
  <li><a href="/work">Work</a></li>
  <li><a href="/blog">Blog</a></li>
  <li><a href="/contact">Contact</a></li>

$lines = explode("\n", $nav);
foreach ($lines as $line) {
    $current = false;
    preg_match('/href="([^"]+)"/', $line, $url);
    if (substr($_SERVER["REQUEST_URI"], 0, 5) == substr(@$url[1], 0, 5)) {
        $line = str_replace('<a h', '<a  class="active" h', $line);
    echo $line."\n";

I’ve also documented a JavaScript version if you want to add class active to menu with JavaScript instead.