DOMDocumentVideoSource
DOMDocumentVideoSource

Reputation: 646

echo current row number csv php

i searched for the other answers but they were all mysql based or over complicated..

my script works fine but i would look to echo line number with the foreach section where i echo results (where iam taking this is to eventually find the line number so i can add a delete line/row command);

function ImportCSV2Array($filename)
{
$row = 0;
$col = 0;

$handle = @fopen($filename, "r");
if ($handle) 
{
    while (($row = fgetcsv($handle, 4096)) !== false) 
    {
        if (empty($fields)) 
        {
            $fields = $row;
            continue;
        }

        foreach ($row as $k=>$value) 
        {
            $results[$col][$fields[$k]] = $value;
        }
        $col++;
        unset($row);
    }
    if (!feof($handle)) 
    {
        echo "Error: unexpected fgets() failn";
    }
    fclose($handle);
}

return $results;

}

$filename = "file.csv";
$csvArray = ImportCSV2Array($filename);

foreach ($csvArray as $row)
{

echo " From: <input type=text name=from value='".$row['from']."'>";
echo "To: <input type=text name=to value='".$row['to']."'>";
echo whatwouldiput-here for line number?;

}

Upvotes: 0

Views: 2044

Answers (1)

Smern
Smern

Reputation: 19076

To keep an index, you could simply do this:

$i = 1;
foreach ($csvArray as $row)
{
   echo " From: <input type=text name=from value='".$row['from']."'>";
   echo "To: <input type=text name=to value='".$row['to']."'>";
   echo "Line number: ".$i;
   $i++;
}

Upvotes: 1

Related Questions