Smith Smith - 8 months ago 65
PHP Question

dynamic navigation in php

How do i implement a dynamic navigation in php?


Home | about | contact | faq | tutorials

i need to automatically generate the links dynamically respectively to each page without much script. e.g i should have all the links without manually entering the links to each other page?

Answer Source

If you just want to display a menu for a known set of pages without re-architecting your current code, how about this:

$pages = array(
    'index.php' => 'Home',
    'about.php' => 'About',
    'contact.php' => 'Contact',
    'faq.php' => 'FAQ',
    'tutorials.php' => 'Tutorials',
) ;

$currentPage = basename($_SERVER['REQUEST_URI']) ;


<div id="menu">
    <ul id="menuList">
        <?php foreach ($pages as $filename => $pageTitle) { 
            if ($filename == $currentPage) { ?>
        <li class="current"><?php echo $pageTitle ; ?></li>
            <?php } else { ?>
        <li><a href="<?php echo $filename ; ?>"><?php echo $pageTitle ; ?></a></li>
            } //if 
         } //foreach 

Put this in its own file, say menu.php, and then include it in each page. Then you can style your menu with CSS.