What are common pitfalls when trying to create a collapsible menu in PHP using arrays?

One common pitfall when trying to create a collapsible menu in PHP using arrays is not properly handling the recursive nature of the menu structure. To solve this, you need to use a recursive function to iterate over the nested arrays and generate the menu HTML dynamically.

<?php

function generateMenu($items) {
    $html = '<ul>';
    
    foreach ($items as $item) {
        $html .= '<li>' . $item['label'];
        
        if (isset($item['children'])) {
            $html .= generateMenu($item['children']);
        }
        
        $html .= '</li>';
    }
    
    $html .= '</ul>';
    
    return $html;
}

$menu = [
    ['label' => 'Home'],
    ['label' => 'About', 'children' => [
        ['label' => 'Company'],
        ['label' => 'Team'],
    ]],
    ['label' => 'Services'],
];

echo generateMenu($menu);

?>