How can recursion be used to simplify the process of handling nested arrays in PHP?

Handling nested arrays in PHP can be complex and tedious due to the potentially infinite levels of nesting. Recursion can simplify this process by allowing a function to call itself within the function, effectively traversing through all levels of the nested array without the need for multiple nested loops.

function flattenArray($array) {
    $result = [];
    
    foreach ($array as $element) {
        if (is_array($element)) {
            $result = array_merge($result, flattenArray($element));
        } else {
            $result[] = $element;
        }
    }
    
    return $result;
}

$nestedArray = [1, 2, [3, 4, [5, 6]], 7];
$flattenedArray = flattenArray($nestedArray);

print_r($flattenedArray);