How can nested navigation menus be implemented in PHP to ensure both parent and child items receive an active class?

When implementing nested navigation menus in PHP, it can be challenging to ensure that both parent and child items receive an active class when selected. One way to solve this issue is by using a recursive function to iterate through the menu items and check if the current page matches the menu item. If it does, both the parent and child items can be marked as active.

function generateMenu($menuItems, $currentPage) {
    echo '<ul>';
    foreach ($menuItems as $item) {
        echo '<li';
        if ($item['url'] == $currentPage) {
            echo ' class="active"';
        }
        echo '>';
        echo '<a href="' . $item['url'] . '">' . $item['title'] . '</a>';
        if (!empty($item['children'])) {
            generateMenu($item['children'], $currentPage);
        }
        echo '</li>';
    }
    echo '</ul>';
}

// Usage
$menu = [
    ['title' => 'Home', 'url' => 'index.php'],
    ['title' => 'About', 'url' => 'about.php'],
    ['title' => 'Services', 'url' => 'services.php', 'children' => [
        ['title' => 'Web Design', 'url' => 'webdesign.php'],
        ['title' => 'SEO', 'url' => 'seo.php'],
    ]],
    ['title' => 'Contact', 'url' => 'contact.php'],
];

$current_page = 'services.php';
generateMenu($menu, $current_page);