The Shortest PHP Code to Convert CSV to an Associative Array

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

  1. file('data.csv') reads the CSV file into an array of lines
  2. array_map('str_getcsv', ...) converts each line into an array
  3. array_walk combines each row with the headers (first row) to create associative arrays
  4. array_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!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top