Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Add comma to every item but last one

Tags:

php

for-loop

csv

I have a loop like

foreach ($_GET as $name => $value) {
    echo "$value\n";
}

And I want to add a comma in between each item so it ends up like this.

var1, var2, var3

Since I am using foreach I have no way to tell what iteration number I am on.

How could I do that?

like image 503
giodamelio Avatar asked Mar 26 '11 05:03

giodamelio


2 Answers

Just build your output with your foreach and then implode that array and output the result :

$out = array();
foreach ($_GET as $name => $value) {
    array_push($out, "$name: $value");
}
echo implode(', ', $out);
like image 196
Yanick Rochon Avatar answered Sep 28 '22 14:09

Yanick Rochon


Like this:

$total = count($_GET);
$i=0;
foreach ($_GET as $name => $value) {
    $i++;
    echo "$name: $value";
    if ($i != $total) echo', ';
}

Explained: you find the total count of all values by count(). When running the foreach() loop, you count the iterations. Inside the loop you tell it to echo ', ' when the iteration isn't last (isn't equal to total count of all values).

like image 45
Frantisek Avatar answered Sep 28 '22 16:09

Frantisek