Skip to content
PHP Logo

How can the code snippet provided be modified to handle CSV files with more than two columns?

The issue with the current code snippet is that it assumes the CSV file has only two columns, so it only reads and outputs the first two columns. To handle CSV files with more than two columns, we need to modify the code to loop through all columns in each row and output them accordingly. This can be achieved by using a nested loop to iterate through each row and then through each column within that row.

php
<?php

$csvFile = 'example.csv';
$csvData = array_map('str_getcsv', file($csvFile));

foreach ($csvData as $row) {
    foreach ($row as $column) {
        echo $column . " | ";
    }
    echo "\n";
}

?>