How can I easily remove the last comma from an array?

前端 未结 10 1107
予麋鹿
予麋鹿 2020-12-04 01:50

Let\'s say I have this:

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

foreach($array as $i=>$k)
{
echo $i.\'-\'.$         


        
10条回答
  •  遥遥无期
    2020-12-04 02:34

    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.

提交回复
热议问题