Remove comma from the last foreach value in PHP [duplicate]

3

Good morning,

I have a foreach in my system and I need to separate the pro comma items, so the foreach is like this

foreach($value as $item){ echo $item . ','}

The result obviously comes out:

1,2,3,

How do I get this last comma, regardless of the number of items I have in the array?

    
asked by anonymous 05.09.2016 / 16:04

2 answers

2

There are several ways. You can do with rtrim :

$array = [1,2,3,4];
$text = '';
foreach($array as $item) {
    $text .= $item. ', ';
}
$text = rtrim($text, ', ');
echo $text; // 1, 2, 3, 4

Or for example, like this:

$array = [1,2,3,4];
$arrayCount = count($array);
for($i=0; $i < $arrayCount; $i++) {
    if($i < $arrayCount-1) { // fazemos isto para todas as voltas menos para a ultima
        echo $array[$i]. ',';
        continue;
    }
    echo $array[$i]; // na ultima volta não acrescenta a virgula... 1,2,3,4
}

To complement I will leave here the solution above but with foreach:

$array = [1,2,3,4];
$arrayCount = count($array);
$i = 0;
foreach($array as $item) {
    if(++$i === $arrayCount) { // fazemos isto para todas as voltas menos para a ultima
        echo $item;
        continue;
    }
    echo $item. ','; // na ultima volta não acrescenta a virgula... 1,2,3,4
}
    
05.09.2016 / 16:08
5

You can also use implode(",", $array); instead of foreach .

    
05.09.2016 / 16:14