Skip to content
PHP Logo

What are some alternative ways to populate the $selection variable in PHP for marking active menu items?

When building a website with multiple pages, it is common to have a navigation menu where the active page is highlighted. One way to achieve this in PHP is by using the $_SERVER['REQUEST_URI'] variable to get the current page URL and compare it with the menu item URLs. If they match, we can set the $selection variable to 'active' to mark the menu item as active.

php
<?php
$current_page = $_SERVER['REQUEST_URI'];
$selection = '';

// Define an array of menu items and their corresponding URLs
$menu_items = array(
    'Home' => '/',
    'About' => '/about',
    'Services' => '/services',
    'Contact' => '/contact'
);

// Loop through the menu items and check if the current page matches the URL
foreach ($menu_items as $item => $url) {
    if ($url == $current_page) {
        $selection = 'active';
        break;
    }
}

// Output the menu items with the active class
foreach ($menu_items as $item => $url) {
    echo '<li class="' . ($url == $current_page ? 'active' : '') . '"><a href="' . $url . '">' . $item . '</a></li>';
}
?>