Skip to content
PHP Logo

How can PHP developers prevent errors when using array_unique() on CSV data in PHP?

When using array_unique() on CSV data in PHP, developers should be aware that the function may not work as expected due to the data type inconsistency in CSV files. To prevent errors, developers can first convert the CSV data into an array and then use array_map() to apply trim() function to remove any leading or trailing spaces. Finally, developers can use array_unique() to remove any duplicate values in the array.

php
// Read CSV data into an array
$csvData = array_map('str_getcsv', file('data.csv'));

// Apply trim() function to remove leading/trailing spaces
$trimmedData = array_map(function($row) {
    return array_map('trim', $row);
}, $csvData);

// Remove duplicate values using array_unique()
$uniqueData = array_map('unserialize', array_unique(array_map('serialize', $trimmedData)));

// Print the unique data
print_r($uniqueData);