Skip to content
PHP Logo

How can one differentiate between an indexed array and an associative array when reading data from a CSV file in PHP?

When reading data from a CSV file in PHP, one can differentiate between an indexed array and an associative array by examining the header row of the CSV file. If the header row contains column names, then the data should be read into an associative array where the column names serve as keys. If the header row is absent or does not contain column names, then the data should be read into an indexed array where each row is represented as a numerical index.

php
// Assuming $file contains the path to the CSV file
$handle = fopen($file, "r");
$data = [];
$header = fgetcsv($handle); // Read the header row

// Check if the header row exists and is not empty
if ($header !== false && !empty($header)) {
    // Read data into an associative array
    while (($row = fgetcsv($handle)) !== false) {
        $data[] = array_combine($header, $row);
    }
} else {
    // Read data into an indexed array
    while (($row = fgetcsv($handle)) !== false) {
        $data[] = $row;
    }
}

fclose($handle);

// $data now contains either an indexed array or an associative array based on the presence of a header row in the CSV file