How can arrays be utilized to simplify the process of marking menu items based on the active page in PHP?
When marking menu items based on the active page in PHP, arrays can be utilized to store the page names and their corresponding CSS classes. By using an array to map page names to CSS classes, we can easily determine which menu item should be marked as active based on the current page being viewed.
<?php
// Define an array mapping page names to CSS classes
$menuItems = [
'home' => 'inactive',
'about' => 'inactive',
'services' => 'inactive',
'contact' => 'inactive'
];
// Get the current page name from the URL
$current_page = basename($_SERVER['REQUEST_URI'], ".php");
// Mark the active page by changing its CSS class in the array
if (array_key_exists($current_page, $menuItems)) {
$menuItems[$current_page] = 'active';
}
// Output the menu items with their corresponding CSS classes
foreach ($menuItems as $page => $class) {
echo '<li class="' . $class . '">' . ucfirst($page) . '</li>';
}
?>
Keywords
Related Questions
- What are the advantages of using arrays in PHP for managing random numbers?
- What are some best practices for creating a recurring event feature in PHP, considering factors like holidays and skipped weeks?
- Is it possible to prevent errors in PHP by checking for objects before performing actions on them?