Search code examples
phparraysforeachundefinedoffset

Not sure how to resolve this particular undefined offset issue


Hello guys,

I am relatively new to Php, so go easy on me. Having said that, the output of the code is exactly what I am expecting ( a table of 6 columns and n rows ).My problem is that I have 5 notifications at the end of the table of undefined offset 1, 2 ,3 ,4 ,5 (indicating the lines $result[1]...$result[5];

By printing the array I am also noticing at the end of it Array ( [0] => [1] => [2] => [3] => [4] => [5] => ) maybe that is the problem, the index being set to nothing, but I hate 'maybe' so I am quite stuck at the moment.

Thanks in advance

$csvData = file_get_contents('excel_csv.csv');
$lines = explode(PHP_EOL, $csvData);

$array = array();
foreach ($lines as $line) {
    $array[] = str_getcsv($line);
}

echo "<table class='main-table'>";
    foreach($array as $result) {
           echo "<tr class='main-row'>
             <td class='main-column'><img src='poze/$result[0]'/></td>  
             <td class='main-column'>$result[1]</td>   
             <td class='main-column'>$result[2]</td>  
             <td class='main-column'>$result[3]</td>
             <td class='main-column'>$result[4]</td>  
             <td class='main-column'>$result[5]</td>   
            </tr>";
    }
echo "</table>";

Solution

  • change 1st tow line

    $csvData = file_get_contents('excel_csv.csv');
    $lines = explode(PHP_EOL, $csvData);
    

    with

    $lines = file('excel_csv.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    

    to avoid empty lines