Remove comma from the last foreach value in PHP

Asked

Viewed 1,944 times

3

Good morning,

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

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

the result obviously comes out:

1,2,3,

how do I take this last comma, regardless of the number of items I have in the array ?

2 answers

5

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

2


There are several ways. 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 ex, 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 up 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
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.