What are the best practices for maintaining active or highlighted states in navigation menus when using PHP?
When building navigation menus in PHP, it's important to maintain active or highlighted states on the current page to provide visual feedback to users. One way to achieve this is by adding a CSS class to the active menu item based on the current URL. This can be done by comparing the current URL with the URL of each menu item and adding the active class if they match.
<?php
$current_url = $_SERVER['REQUEST_URI'];
function is_active($url)
{
global $current_url;
if ($current_url == $url) {
echo 'active';
}
}
?>
<ul>
<li class="<?php is_active('/home.php'); ?>"><a href="/home.php">Home</a></li>
<li class="<?php is_active('/about.php'); ?>"><a href="/about.php">About</a></li>
<li class="<?php is_active('/contact.php'); ?>"><a href="/contact.php">Contact</a></li>
</ul>