Hello I'm trying to make my navigation bar active in php, so that user can know in which page they are on. I'm new to php and don't know much about it. So how can I add a class="active" in this code to make a active nav bar and display all the page in same index.php page.
<a href="?page=home"> Home</a></br>
<a href="?page=news"> News</a></br>
<a href="?page=about"> About</a></br>
<a href="?page=contact"> Contact</a></br>
<?php
if (!isset($_GET['page'])) {
include "home.php";
} else {
switch ($_GET['page']) {
case "home":
include "home.php";
break;
case "news":
include "news.php";
break;
case "about":
include "about.php";
break;
case "contact":
include "contact.php";
break;
default:
include "home.php";
};
}
?>
Try this code:
Create an array of menu items and then use a
foreach
loop to generate the menu dynamically.That way when you add new items to the array they will show up in the menu:
You should replace all of your code with this code and give it a spin. Using loops to reduce the amount of redundant markup you need to write is not only DRY but will save you a lot of time in the future!
You can use the PHP code below as navigation. I recommend that you use unordered list (i.e.
<ul><li><a href=""></a></li></ul>
) tags for navigation:Then add the below style to CSS: