How can one ensure that data is correctly mapped to the appropriate columns when reading a CSV file in PHP?

When reading a CSV file in PHP, it is important to ensure that the data is correctly mapped to the appropriate columns. One way to do this is by using the fgetcsv() function to read each line of the CSV file and then manually assigning each value to the corresponding column in an associative array. This way, you can easily access the data by its column name.

// Open the CSV file for reading
$handle = fopen('data.csv', 'r');

// Initialize an empty array to store the data
$data = [];

// Read the CSV file line by line
while (($row = fgetcsv($handle)) !== false) {
    // Assign each value to the appropriate column in the associative array
    $data[] = [
        'column1' => $row[0],
        'column2' => $row[1],
        'column3' => $row[2],
        // Add more columns as needed
    ];
}

// Close the file handle
fclose($handle);

// Access the data by column name
foreach ($data as $row) {
    echo $row['column1'] . ' - ' . $row['column2'] . ' - ' . $row['column3'] . PHP_EOL;
}