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>';
}
?>