How can PHP code be optimized to only display specific columns from a CSV file?

To optimize PHP code to only display specific columns from a CSV file, you can read the CSV file line by line, explode each line into an array, and then access only the specific columns you want to display. This approach avoids loading the entire CSV file into memory and allows you to selectively display the desired columns.

<?php

$csvFile = 'data.csv';
$specificColumns = [0, 2]; // Columns to display (0-based index)

if (($handle = fopen($csvFile, 'r')) !== false) {
    while (($data = fgetcsv($handle)) !== false) {
        $output = [];
        foreach ($specificColumns as $col) {
            $output[] = $data[$col];
        }
        echo implode(', ', $output) . PHP_EOL;
    }
    fclose($handle);
}

?>