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?
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 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With