开发者

PHP Add comma to every item but last one

开发者 https://www.devze.com 2023-02-19 16:58 出处:网络
I have a开发者_StackOverflow社区 loop like foreach ($_GET as $name => $value) { echo \"$value\\n\";

I have a开发者_StackOverflow社区 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).


$comma_separated = implode(", ", $_GET);

echo $comma_separated;

you can use implode and achieve that


You could also do it this way:

$output = '';
foreach ($_GET as $name => $value) {
    $output = $output."$name: $value, ";
}
$output = substr($output, 0, -2);

Which just makes one huge string that you can output. Different methods for different styles, really.


Sorry I did not state my question properly. The awnser that worked for me is

implode(', ', $_GET);

Thanks, giodamelio


I'd typically do something like this (pseudo code):

myVar

for... {
    myVar = i + ","
}

myVar = trimOffLastCharacter(myVar)

echo myVar
0

精彩评论

暂无评论...
验证码 换一张
取 消