What is the best approach to highlight an active navigation link in PHP when a new page is loaded?
When a new page is loaded in PHP, you can highlight the active navigation link by checking the current page URL against the navigation link URLs. If there is a match, you can apply a CSS class to style the active link differently. This can be achieved by using a combination of PHP and HTML to dynamically set the active class based on the current page.
<?php
// Get the current page URL
$current_url = $_SERVER['REQUEST_URI'];
// Define an array of navigation links and their corresponding URLs
$nav_links = array(
'Home' => '/index.php',
'About' => '/about.php',
'Services' => '/services.php',
'Contact' => '/contact.php'
);
// Loop through the navigation links and check if the current URL matches
foreach($nav_links as $title => $url) {
$active_class = ($current_url == $url) ? 'active' : '';
echo '<a href="' . $url . '" class="' . $active_class . '">' . $title . '</a>';
}
?>
Keywords
Related Questions
- In what scenarios would the function "count" in PHP return an empty or non-existent object, causing the mentioned error?
- What considerations should PHP developers keep in mind when designing database structures to avoid duplicate entries and ensure data integrity when working with JSON data?
- What are the advantages and disadvantages of using nodeJS compared to PHP for real-time user online tracking?