Nisanth Kumar
Nisanth Kumar

Reputation: 5715

Print column of array of objects as comma-separated string with no trailing comma

I have the following code in html:

<? foreach($tst as $test) : ?>
    <?=$test->id?>,
<? endforeach ?>

and that will result as test1,test2,test3,

How avoid that last comma in simple method. I can't use complicated code in html like:

<? $i = 0; ?>
<? foreach($tst as $test) : ?>
    <?= $test->id ?>,
<? endforeach ?>
<? $i++; ?>
<? if($i != count($tst)) :?>
    ,
<? endif; ?>

Upvotes: 1

Views: 112

Answers (1)

leepowers
leepowers

Reputation: 38318

Use implode on an interim array:

<?php

$a= array();

foreach($tst as $test) {
 $a[]= $test->id;
}

echo(implode(', ', $a));

?>

Upvotes: 5

Related Questions