Shortest PHP code to convert CSV to associative array

By Joel Stein on December 8, 2012

There are tons of code snippets out there to convert a CSV file to an associative array, where the first line contains the column headings for the rest of the file. Most of them were really long, but I came up with what I think is the shortest way to accomplish this in PHP.

$rows = array_map('str_getcsv', file('myfile.csv'));
$header = array_shift($rows);
$csv = array();
foreach ($rows as $row) {
  $csv[] = array_combine($header, $row);

One thing for you Mac users. You may have to include this line at the top, to correct PHP’s detection of line endings:

ini_set('auto_detect_line_endings', TRUE);

If you have a shorter way, let’s see it!