How can PHP developers efficiently control the depth of recursion in menu generation to avoid overwhelming the system?

To efficiently control the depth of recursion in menu generation, PHP developers can use a parameter to track the current depth level and limit the recursion accordingly. By checking the depth level before making a recursive call, developers can prevent the system from being overwhelmed by excessive recursion.

function generateMenu($items, $depth = 0, $maxDepth = 3) {
    if ($depth >= $maxDepth) {
        return; // stop recursion if depth limit reached
    }
    
    echo '<ul>';
    foreach ($items as $item) {
        echo '<li>' . $item['label'] . '</li>';
        if (!empty($item['children'])) {
            generateMenu($item['children'], $depth + 1, $maxDepth);
        }
    }
    echo '</ul>';
}

// Example usage
$items = [
    ['label' => 'Home'],
    ['label' => 'About', 'children' => [
        ['label' => 'Team'],
        ['label' => 'History'],
    ]],
    ['label' => 'Services', 'children' => [
        ['label' => 'Web Development'],
        ['label' => 'Mobile Development', 'children' => [
            ['label' => 'iOS'],
            ['label' => 'Android'],
        ]],
    ]],
];

generateMenu($items);