Smith Smith - 8 days ago 6
PHP Question

dynamic navigation in php

How do i implement a dynamic navigation in php?

e.g

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

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

<?php
$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>
            <?php
            } //if 
         } //foreach 
            ?>
    </ul>
</div>

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

Comments