How can the issue of duplicate entries in the CSV output be prevented when using fputcsv in PHP?

When using fputcsv in PHP to output data to a CSV file, duplicate entries can occur if the data being written contains the same values. To prevent this issue, you can check if the data being written already exists in the file before writing it. This can be done by reading the file line by line and comparing the data with the new entry before writing it.

// Open the CSV file for reading and writing
$csvFile = fopen('data.csv', 'a+');

// Check if the data being written already exists in the file
while (($row = fgetcsv($csvFile)) !== false) {
    if ($row == $data) {
        // Data already exists, do not write duplicate entry
        fclose($csvFile);
        return;
    }
}

// If data does not exist, write the new entry to the CSV file
fputcsv($csvFile, $data);

// Close the CSV file
fclose($csvFile);