Convert The CSV Data to Associative Array

PHP CSV Array

Most of the time we have some csv data of any no of column and we want to convert that in an associative array, so that can be utilize anywhere we need. This function will help you for the same.

function csvToAssocArray($csvFile) {
 $row = 0;
 $resultSet = array();
 if (($handle = fopen($csvFile, "r")) !== FALSE) {
  $dataCtr = 0;
  $dataLabel = array();
  
  while (($data = fgetcsv($handle, 10000, "\t")) !== FALSE) {
   $num = count($data);
   for ($c=0; $c < $num; $c++) {
    if($row==0) $dataLabel[] = $data[$c];                     //First row as heading as key for the associative array
    else        $resultSet[$row][$dataLabel[$c]] = $data[$c]; //other row to map the data with associative array
   }
   $row++;
  }
  fclose($handle);
 } //End of while

 return count($resultSet):$resultSet?false; //If no data return false;
}