How can you optimize your code when working with nested arrays in PHP to improve performance and readability?

When working with nested arrays in PHP, one way to optimize your code for better performance and readability is to use recursive functions to iterate through the nested arrays. This approach helps to avoid repetitive code and makes it easier to handle arrays of varying depths.

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

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

print_r($flattenedArray);