PHP dynamic menu generation with selected class and dynamic title insert

I was recently working on a website , there was many in the market solutions available to achieve the above task. But being a programmer I wanted to do something on my own and a bit different. The solution is quite neat and flexible.

The Problem: Blog type website with many menu items. That need to be dynamic to add ‘selected’ class to css of the pge menu

The solution:

switch($pg)
{
case 'page1' :
$tit = 'Home'; // this will insert dynamic title
break;
case 'page2' :
$tit = 'Movies';
break;
case 'page3' :
$tit = 'Entertainment';
break;
case 'page4' :
$tit = 'Arts & Culture';
break;
case 'page5' :
$tit = 'Travel & Living';
break;
case 'page6' :
$tit = 'Fashion';
break;
case 'page7' :
$tit = 'News';
break;
case 'page8' :
$tit = 'Popular';
break;
default:
$tit = 'More';
}</code>

// function to add a class to menu is
$chosenMenu = $pg; include('menu.php');

the menu.php file itself is as follows:

$menuItems = array(
'page1'=&gt;'Home.php',
'page2'=&gt;'Movies.php',
'page3'=&gt;'Entertainment.php',
'page4'=&gt;'Arts &amp; Culture.php',
'page5'=&gt;'Travel &amp; living.php',
'page6'=&gt;'Fashion.php',
'page7'=&gt;'News.php',
'page8'=&gt;'Popular.php',
'page9'=&gt;'more.php',

);
<code>
foreach($menuItems as $key =&gt; $value) {
    echo href=$valueif (isset($chosenMenu) &amp;&amp; $chosenMenu == $key) echo ' class="selected"';
	$str = substr($value, 0, strrpos($value, '.'));
    echo '&gt;'.$str.';
}

Hope You enjoy the solution:

Suggestions are welcome
Happy Coding
Shakeel

Leave a comment

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