michaelmcgurk michaelmcgurk - 2 months ago 9
PHP Question

Remove comma from last item in while loop

I have the following code which opens a CSV file and exports the results to a JSON format.

However, I'd like to remove the last

,
from the while loop. Can someone explain how I do this with my current code?

<?php
ini_set('max_execution_time', 300);
$wantedColumns = array(3);
$row = 1;
if (($handle = fopen("data.csv", "r")) !== FALSE) {

echo '{
"data":
[';

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<tr>';
}else{
echo '<tr>';
}

for ($c=0; $c < $num; $c++) {
if (!in_array($c,$wantedColumns)) continue;



if(empty($data[$c])) {
$value = "&nbsp;";
}else{
$value = $data[$c];
}

if ($row == 1) {
}else{
echo ''.$value.','; // comma added here
}
}

if ($row == 1) {
echo '</tr>';
}else{
echo '</tr>';
}

$row++;
//$value= substr($value, 0, -1);
}
echo ' ]
}';

echo '</tbody></table>';
echo '</center>';
fclose($handle);
}
?>

Answer

When doing things like this, I prefer to push the values on to an array and then use implode to join them up

    $values = array();
    for ($c=0; $c < $num; $c++) {
        if (!in_array($c,$wantedColumns)) continue;



        if(empty($data[$c])) {
           $value = "&nbsp;";
        }else{
           $value = $data[$c];
        }

        if ($row == 1) {
        }else{
            $values[] = $value;
        }
    }

    echo implode(',', $values);