Convert CSV data into an associative array

If you want to convert comma separated values into an associated array, then use the following code.

Note: The code uses the first row of your CSV data to determine the keys in the associative array.

 * Convert a comma separated file into an associated array.
 * The first row should contain the array keys.
 * Example:
 * @param string $filename Path to the CSV file
 * @param string $delimiter The separator used in the file
 * @return array
 * @link
 * @author Jay Williams <>
 * @copyright Copyright (c) 2010, Jay Williams
 * @license MIT License
function csv_to_array($filename='', $delimiter=',')
	if(!file_exists($filename) || !is_readable($filename))
		return FALSE;

	$header = NULL;
	$data = array();
	if (($handle = fopen($filename, 'r')) !== FALSE)
		while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
				$header = $row;
				$data[] = array_combine($header, $row);
	return $data;

Found here, courtesy of jaywilliams

4 thoughts on “Convert CSV data into an associative array

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s