What are some best practices for creating dynamic menus in PHP?

When creating dynamic menus in PHP, it is best practice to store the menu items in a database or an array to easily update and manage them. You can then loop through the menu items to generate the menu dynamically based on the data. Using a recursive function can be helpful for creating multi-level menus.

<?php
// Sample array of menu items
$menuItems = array(
    array('title' => 'Home', 'url' => 'index.php'),
    array('title' => 'About', 'url' => 'about.php'),
    array('title' => 'Services', 'url' => 'services.php', 'children' => array(
        array('title' => 'Web Design', 'url' => 'web-design.php'),
        array('title' => 'Graphic Design', 'url' => 'graphic-design.php')
    )),
    array('title' => 'Contact', 'url' => 'contact.php')
);

function buildMenu($items) {
    echo '<ul>';
    foreach ($items as $item) {
        echo '<li><a href="' . $item['url'] . '">' . $item['title'] . '</a>';
        if (isset($item['children'])) {
            buildMenu($item['children']);
        }
        echo '</li>';
    }
    echo '</ul>';
}

buildMenu($menuItems);
?>