#native_company# #native_desc#

Dynamic Site Navigation for Your Users

By Eli White III and Jonathan Eisenhamer
on September 13, 2006

Although a site may not always warrant a full multilayer navigation menu, most websites usually have at least a few different sections. Often many pages have links back to the top pages of each section, and therefore it is useful to highlight which section the user is currently in. Listing 9.2.1 looks at the URL of the current web page and, based on that, determines what section of the website it is in and changes the section menu.

Listing 9.2.1 Navigation Highlighting

// Now create a function that will highlight the
// section you are in:
function create_highlighted_sections($secarray) {

  // Loop over the entire array,
  // making a basic menu:
  echo "<ul>n";
  foreach ($secarray as $section => $url) {

    // Echo out a link for this section,
    // highlighting if currently in it
    $class = '';
    if (strncmp($url, $_SERVER['PHP_SELF'],
      strlen($url)) == 0) {
        $class = ' class="current"';
    echo "<li{$class}><a href="{$url}">
  echo "</ul>n";

// An array with all section names and
// the URL to their top directory:
$sections = array(
  'News' => '/news/',
  'Photos' => '/media/pictures/',
  'Video' => '/media/movies/',
  'Stuff' => '/eliw/'

// Output a little bit of CSS to
// accomplish the highlighting:
.current, .current a { color: red }
// And call the function to test it:
As currently coded this just generates a basic UL list and assigns a class to the current section. This can be modified now via CSS to display in whatever manner you want, or the function can be extended to create different XHTML as needed.
The primary trick in this function is that it compares the current value of PHP_SELF to its list of sections. In this manner it can determine what section the current file is within. Of course this relies on the fact that your sections will each be in their own subdirectory. A nice side effect of this setup is that if a file lives at the top level, or within a different subdirectory, no section will be highlighted, because, obviously, you are not in any of those sections.

This article is taken from the chapter titled, “Web Page Creation/XHTML/CSS”, which is excerpted from the new book, PHP 5 in Practice, authored by Eli White III and Jonathan Eisenhamer. Copyright 2007 by Sams Publishing. ISBN 0672328887. Reprinted with permission by Pearson Education; All rights reserved. A complete Table of Contents is available online.