How can PHP be used to dynamically display different menu items on different pages?
To dynamically display different menu items on different pages using PHP, you can create an associative array where the keys represent the page names and the values represent the menu items for that page. Then, you can use the current page name to retrieve the corresponding menu items from the array and display them on the page.
<?php
// Define an associative array of menu items for each page
$menuItems = [
"home.php" => ["Home", "About Us", "Contact Us"],
"products.php" => ["Products", "Services", "FAQ"],
"services.php" => ["Services", "Portfolio", "Testimonials"]
];
// Get the current page name
$current_page = basename($_SERVER['PHP_SELF']);
// Display the menu items for the current page
foreach ($menuItems[$current_page] as $menuItem) {
echo "<li>$menuItem</li>";
}
?>
Keywords
Related Questions
- How can PHP beginners effectively utilize external files to streamline database queries?
- What resources or documentation can PHP beginners refer to for understanding and implementing secure coding practices in PHP?
- How can SQL injections be prevented in PHP scripts, especially in forms that interact with databases?