Skip to content
PHP Logo

How can both arrays be merged and written to a CSV file in PHP, as discussed in the forum thread?

To merge both arrays and write them to a CSV file in PHP, you can use the `array_merge` function to combine the arrays, and then use `fputcsv` to write the merged data to a CSV file. Make sure to open the CSV file in write mode and properly handle the file pointer. Additionally, loop through the merged array to write each row to the CSV file.

php
// Merge the two arrays
$mergedArray = array_merge($array1, $array2);

// Open the CSV file in write mode
$fp = fopen('output.csv', 'w');

// Loop through the merged array and write each row to the CSV file
foreach ($mergedArray as $row) {
    fputcsv($fp, $row);
}

// Close the file pointer
fclose($fp);