1

How to remove last comma from the output of a foreach() loop?

Can someone please help modify this code for me.

$sth = $dbh->query('SELECT * FROM `stage5` ORDER BY `stage5`.`lenght` DESC');
$sth->setFetchMode(PDO::FETCH_ASSOC);
$result = $sth->fetchAll();

foreach($result as $r) {
     echo $r['lenght'], ",";
}        

This prints
105.4,102.1,

Below would be correct
105.4,102.1

I have read many posts related to this but, I can't get it working and I don't get it. Any help is appreciated!

Will
  • 24,082
  • 14
  • 97
  • 108
Paavo Doe
  • 57
  • 8
  • Yes, I did know there is other posts, but being beginner with PHP, I tried many options and Googled but didn't get it working. So I posted my actual code on question. – Paavo Doe Jun 09 '16 at 11:29

2 Answers2

8

One way to solve this is to not echo out the commas in the foreach loop. Put the data you want to echo into an array, then use implode.

$output = array();
foreach($result as $r) {
    $output[] = $r['lenght'];
}

echo implode(',', $output);
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
3

I would just take a functional approach:

<?php
$result = $sth->fetchAll();
echo implode(',', array_column($result, 'length'));

Note that array_column() requires PHP 5.5+.

Will
  • 24,082
  • 14
  • 97
  • 108