How can PHP developers avoid repetitive code when processing multiple arrays for CSV output?

To avoid repetitive code when processing multiple arrays for CSV output, PHP developers can create a reusable function that takes an array as input and generates CSV output. By abstracting the CSV generation logic into a function, developers can easily call this function for each array they need to process, reducing code duplication.

function generateCsvFromArray($array) {
    $output = fopen('php://output', 'w');
    foreach ($array as $row) {
        fputcsv($output, $row);
    }
    fclose($output);
}

// Example usage
$array1 = [
    ['John', 'Doe', 'john.doe@example.com'],
    ['Jane', 'Smith', 'jane.smith@example.com']
];

$array2 = [
    ['Alice', 'Johnson', 'alice.johnson@example.com'],
    ['Bob', 'Brown', 'bob.brown@example.com']
];

generateCsvFromArray($array1);
generateCsvFromArray($array2);