In what situations does the PHP code successfully handle menus with submenus, and where does it encounter errors?
When handling menus with submenus in PHP, the code may encounter errors when trying to properly display nested submenus. To successfully handle menus with submenus, it is essential to use recursive functions to traverse through the menu items and their submenus. This approach ensures that all levels of submenus are properly displayed without encountering errors.
function display_menu($menu_items) {
echo '<ul>';
foreach ($menu_items as $item) {
echo '<li>' . $item['label'];
if (isset($item['submenu']) && !empty($item['submenu'])) {
display_menu($item['submenu']);
}
echo '</li>';
}
echo '</ul>';
}
$menus = [
[
'label' => 'Home',
'submenu' => []
],
[
'label' => 'Products',
'submenu' => [
[
'label' => 'Product 1',
'submenu' => []
],
[
'label' => 'Product 2',
'submenu' => [
[
'label' => 'Subproduct 1',
'submenu' => []
]
]
]
]
],
[
'label' => 'Contact',
'submenu' => []
]
];
display_menu($menus);