PHP: Convert CSV String to a Pretty Assoc Array
Submitted by admin on Mon, 09/08/2025 - 9:05am
Sometimes you find yourself with a CSV string (not a file on the filesystem), and you'd like to use str_getcsv to get an array, but the results are sloppy and not at all friendly to work with. Reading from a file on the filesystem is more memory-friendly, but sometimes that just isn't the situation you have.
If you think this applies to you, check out the following function.
It creates an assoc array from a CSV string, where the header value is used as the array's keys.
Code:
function csv_multiline_to_array($csv_str, $bool_first_row_is_headers = TRUE) { $csv = array_map('str_getcsv', explode("\n", trim($csv_str))); array_walk($csv, function(&$a) use ($csv) { if (count($a) == count($csv[0])) { $a = array_combine($csv[0], $a); } else { // Error converting CSV to an array. Not the same number of elements. // Perform whatever action desired. Eg, return FALSE; } }); if ($bool_first_row_is_headers) { array_shift($csv); // remove column header } return $csv; }
So, the following:
Name,Location,Type Armstrong Middle School,Acadia Parish,Elementary Branch Elementary School,Acadia Parish,Middle School
Results in this array:
[0]['Name'] = 'Armstrong Middle School' ['Location'] = 'Acadia Parish' ['Type'] = 'Elementary' [1]['Name'] = 'Branch Elementary' ['Location'] = 'Acadia Parish' ['Type'] = 'Middle School'
Hopefully someone finds this useful!