Sevencolors studies:
experiments with Javascript, CSS, PHP and web standards

Printer icon

PHP menu

A PHP menu

The PHP code:

<?php
// the logic is just the following function
function make_menu($nav_el){
$current_url = $_SERVER['PHP_SELF'];
echo("<ul class=\"nav\">\n");
foreach($nav_el as $key=>$val){
if($val == "subnav") echo("<li>$key</li>\n");
list($href, $title) = explode(":",$val);
if($href!=$current_url && $val != "subnav") echo("<li><a href=\"$href\" title=\"$title\">$key</a></li>\n");
if($href==$current_url && $val != "subnav") echo("<li class=\"here\" title=\"$title\">$key</li>\n");
} // close the foreach loop
echo("</ul>\n");
}
?>
<?php
$site_nav = array(
"site nav" => "subnav",
"log" => "/php_sql/index.php:Thoughts and ideas",
"links" => "/php_sql/links/index.php:Web design links and references - XFN friendly"
);

$studies = array(
"studies" => "subnav",
"code" => "/php_sql/studies/index.php:CSS, Javascript and PHP experiments"
);

$archives = array(
"archives" => "subnav",
"2004" => "/php_sql/2004.htm:Archive of all 2004 permanent entries",
"photos" => "/php_sql/photos.htm:Archive of all permanent photos"
);

$fragments = array(
"fragments" => "subnav",
"antispam" => "/php_sql/antispamcontact.htm:Anti spam email contact",
"RSS_feed" => "/php_sql/RSS_feed.htm:How to write and use an RSS file"
);

// get the SITE NAV array and build a menu out of it

make_menu($site_nav);

// get the STUDIES array and build a menu out of it

make_menu($studies);

// get the ARCHIVES array and build a menu out of it

make_menu($archives);

// get the FRAGMENTS array and build a menu out of it

make_menu($fragments);

?>

I wanted to create a menu that I could update without having, as a consequence, to re-publish all the pages of my site. I also wanted to keep the same layout that the previous menu had and using arrays I managed to re-create it complete of title attributes.

Probably the code could be streamlined, since I repeat four times the same thing due to the links being divided in four unordered lists but I couldn't come up with a better solution. I want the menu to appear as four aligned blocks and the only way I know to position the links like that is to use four different unordered lists and float them. I tried nesting an unordered list inside another but I couldn't position them as I wanted.

Just copy, paste and save the code as menu.php (or whatever you want) and include it in all the files you want to have the menu on.

This code is taken as it is from my site, so all links and title attributes should be changed to meet your needs.

Update: added a new category (TOOLS) on 2005/03/27.

Update: fixed faulty code and written a single function called for each unordered list.The function could be transformed into a class or included according to specific needs.(2005/08/08)

Update: I changed the layout since this study was published. The menu does not appear as it was anymore. The concept stays valid.(2006/07/06)