What is the best approach to flatten a nested array in PHP while maintaining the same order of elements?

When flattening a nested array in PHP while maintaining the same order of elements, one approach is to use a recursive function that iterates through each element of the array. If an element is an array, the function recursively calls itself to flatten that nested array. If the element is not an array, it is added to the flattened result. This way, the order of elements is preserved as they are flattened.

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

// Example usage
$nestedArray = [1, [2, 3], [4, [5, 6]]];
$flattenedArray = flattenArray($nestedArray);
print_r($flattenedArray);