How can I easily remove the last comma from an arr

2020-02-07 02:05发布

Let's say I have this:

$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");

foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}

echoes "john-doe,foe-bar,oh-yeah,"

How do I get rid of the last comma?

10条回答
我欲成王,谁敢阻挡
2楼-- · 2020-02-07 02:19

I don't like this idea of using substr at all, since it's the style of bad programming. The idea is to concatenate all elements and to separate them by special "separating" phrases. The idea to call the substring for that is like to use a laser to shoot the birds.

In the project I am currently dealing with, we try to get rid of bad habits in coding. And this sample is considered one of them. We force programmers to write this code like this:

$first = true;
$result = "";
foreach ($array as $i => $k) {
  if (!$first) $result .= ",";
  $first = false;
  $result .= $i.'-'.$k;
}
echo $result;

The purpose of this code is much clearer, than the one that uses substr. Or you can simply use implode function (our project is in Java, so we had to design our own function for concatenating strings that way). You should use substr function only when you have a real need for that. Here this should be avoided, since it's a sign of bad programming style.

查看更多
家丑人穷心不美
3楼-- · 2020-02-07 02:21

Alternatively you can use the rtrim function as:

$result = '';
foreach($array as $i=>$k) {
    $result .= $i.'-'.$k.',';
}
$result = rtrim($result,',');
echo $result;
查看更多
相关推荐>>
4楼-- · 2020-02-07 02:22

see this example you can easily understand

$name = ["sumon","karim","akash"];
foreach($name as $key =>$value){
 echo $value;
 if($key<count($name){
     echo ",";
 }
}
查看更多
闹够了就滚
5楼-- · 2020-02-07 02:28

try this code after foreach condition then echo $result1

$result1=substr($i, 0, -1);
查看更多
我想做一个坏孩纸
6楼-- · 2020-02-07 02:32

this would do:

rtrim ($string, ',')
查看更多
Explosion°爆炸
7楼-- · 2020-02-07 02:37

Assuming the array is an index, this is working for me. I loop $i and test $i against the $key. When the key ends, the commas do not print. Notice the IF has two values to make sure the first value does not have a comma at the very beginning.

foreach($array as $key => $value)
{
    $w = $key;
    //echo "<br>w: ".$w."<br>";// test text
    //echo "x: ".$x."<br>";// test text
    if($w == $x && $w != 0 )
    {
    echo ", ";
    }
    echo $value;
    $x++;
}
查看更多
登录 后发表回答