PHP Add comma to every item but last one

南楼画角 提交于 2020-07-17 07:21:42

问题


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?


回答1:


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);



回答2:


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).




回答3:


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

echo $comma_separated;

you can use implode and achieve that




回答4:


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.




回答5:


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

implode(', ', $_GET);

Thanks, giodamelio




回答6:


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

myVar

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

myVar = trimOffLastCharacter(myVar)

echo myVar


来源:https://stackoverflow.com/questions/5440537/php-add-comma-to-every-item-but-last-one

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!