When working with CSV files in PHP, you often need to convert the data into a more manageable associative array format where the first row serves as keys. Here’s the most concise way to accomplish this:
$csv = array_map('str_getcsv', file('data.csv')); array_walk($csv, fn(&$a) => $a = array_combine($csv[0], $a))); array_shift($csv); // remove header row
How This Code Works
file('data.csv')
reads the CSV file into an array of linesarray_map('str_getcsv', ...)
converts each line into an arrayarray_walk
combines each row with the headers (first row) to create associative arraysarray_shift
removes the header row from the final result
Complete Example with File Handling
For a more robust solution that includes error handling:
if (($handle = fopen("data.csv", "r")) !== FALSE) { $headers = fgetcsv($handle); while (($data = fgetcsv($handle)) !== FALSE) { $result[] = array_combine($headers, $data); } fclose($handle); }
When to Use This
This approach is perfect for:
- Small to medium-sized CSV files
- Quick data processing scripts
- Situations where you need minimal code
For very large CSV files, consider using fgetcsv
with a loop instead to conserve memory.
The beauty of PHP is that you can accomplish complex data transformations with just a few lines of clean, functional code!