How can PHP be used to dynamically highlight selected links in a menu without duplication?
To dynamically highlight selected links in a menu without duplication, you can use PHP to compare the current page URL with the URL of each menu item. If they match, you can add a CSS class to highlight the selected link. This can be achieved by looping through the menu items and checking if the URLs match.
<?php
$current_url = $_SERVER['REQUEST_URI'];
$menu_items = array(
array('url' => '/page1.php', 'label' => 'Page 1'),
array('url' => '/page2.php', 'label' => 'Page 2'),
array('url' => '/page3.php', 'label' => 'Page 3')
);
foreach($menu_items as $item) {
$class = ($item['url'] == $current_url) ? 'active' : '';
echo '<a href="' . $item['url'] . '" class="' . $class . '">' . $item['label'] . '</a>';
}
?>
Keywords
Related Questions
- What are some best practices for managing file permissions in PHP applications to ensure security and proper access control?
- How can one differentiate between an array and an object in PHP?
- What are the benefits of using PDO or MySQLi extensions in PHP for database interactions compared to the mysql extension?