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);
Keywords
Related Questions
- How can variable naming conventions impact the readability and maintainability of PHP code?
- What potential pitfalls should be avoided when using the '&' operator in PHP for string concatenation?
- What are common pitfalls to avoid when automating the process of downloading files from remote servers using PHP?