How can recursion be implemented in PHP to simplify the process of iterating through nested navigation arrays?

When dealing with nested navigation arrays in PHP, recursion can be used to simplify the process of iterating through them. Recursion allows a function to call itself, making it easier to handle nested structures without knowing the depth of the array in advance. By using recursion, you can create a function that can handle any level of nesting within the navigation array.

function printNavigation($navArray, $level = 0) {
    foreach ($navArray as $item) {
        echo str_repeat('-', $level) . $item['label'] . "\n";
        if (isset($item['children'])) {
            printNavigation($item['children'], $level + 1);
        }
    }
}

$navigation = [
    ['label' => 'Home'],
    ['label' => 'About'],
    [
        'label' => 'Services',
        'children' => [
            ['label' => 'Web Development'],
            ['label' => 'Graphic Design']
        ]
    ],
    ['label' => 'Contact']
];

printNavigation($navigation);