How can PHP be used to dynamically highlight active menu items based on the current page in a website?
To dynamically highlight active menu items based on the current page in a website, you can use PHP to check the current URL against the URLs of each menu item. If there is a match, you can apply a CSS class to that menu item to highlight it as active.
<?php
$current_url = $_SERVER['REQUEST_URI'];
$menu_items = array(
'Home' => '/',
'About' => '/about',
'Services' => '/services',
'Contact' => '/contact'
);
foreach ($menu_items as $label => $url) {
if ($current_url == $url) {
echo '<li class="active"><a href="' . $url . '">' . $label . '</a></li>';
} else {
echo '<li><a href="' . $url . '">' . $label . '</a></li>';
}
}
?>