phpstringobjectimplodearray-column

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; ?>

Solution

  • Use implode on an interim array:

    <?php
    
    $a= array();
    
    foreach($tst as $test) {
     $a[]= $test->id;
    }
    
    echo(implode(', ', $a));
    
    ?>