Dynamic Menu in PHP

Steps to creating menu using array in PHP

Step 1 : Create the array for menu

A menu consist of choices where each choice has a text and a link. We represent this text and link in an array. For that we will use simple two-dimensional array.  It could look like Dynamic Menu in PHP

<?php
$menu = array(
'home' => array('text'=>'Home', 'url'=>'index.php'),
'gallery' => array('text'=>'Away', 'url'=>'gallery.php'),
'about us' => array('text'=>'About', 'url'=>'about.php'),
);
?>

Step 2 : Create function to generate HTML for the menu

In this function we will generate the HTML code for the navbar using the array of menu we have created in the above step. We pass the array of menu as the parameter to this function.

<?php
function generateMenu($items) {
$html = "<nav>n";
foreach($items as $item) {
$html .= "<a href='{$item['url']}'>{$item['text']}</a>n";
}
$html .= "</nav>n";
return $html;
}
?>

Step 3 : Call the Function and display result

We call the method and send the array as the argument.

<?php echo GenerateMenu($menu); ?>

And this will display result as :

Home Gallery About US

And it generate the HTML code as :

<nav >
<a href='index.php'>Home</a>
<a href='gallery.php'>Gallery</a>
<a href='about.php'>About Us</a>
</nav>

Step 4: Styling navbar

To style the menu we will add the class to navbar . We send the class name to the function with menu list. asGenerateMenu($items, $class) Dynamic Menu in PHP

<?php
function GenerateMenu($items, $class) {
$html = "<nav class='$class'>n";
foreach($items as $item) {
$html .= "<a href='{$item['url']}'>{$item['text']}</a>n";
}
$html .= "</nav>n";
}
?>
Calling function :
<?php echo GenerateMenu($menu, $navbar); ?>
CSS :
.navbar {display block;background-color:#7f7f7f;font-family:Verdana;padding:0.5em;}
.navbar a {background-color:#999;color:#fff;padding:0.2em;text-decoration:none;}

This will display result as

Creating active menu

To highlight the active menu dynamically we can add the class ‘active’ to the <a> which contains the page from the url. To know the current active item of the navbar we will use $_SERVER[‘REQUEST_URI’]  variable.

$_SERVER[‘REQUEST_URI’] :
$_SERVER is an array which holds information of headers, paths, script locations. Web server creates the entries in the array. $_SERVER[‘REQUEST_URI’] contains the URI of the current page. So if the full path of a page is https://tycheventures.com/html/about.php, $_SERVER[‘REQUEST_URI’] would contain /html/about.php.

So by using the following code we can set the active menu in the PHP:

<?php
function GenerateMenu($items, $class) {
$html = "<nav class='$class'>n";
foreach($items as $item) {
$html .= "<a class="<?php echo ($_SERVER['REQUEST_URI'] == $item['url']) ? 'active':'' ?>" href='{$item['url']}'>{$item['text']}</a>n";
}
$html .= "</nav>n";
}
?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.