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

前端 未结 10 1032
予麋鹿
予麋鹿 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:38

    I always use this method:

    $result = '';
    foreach($array as $i=>$k) {
        if(strlen($result) > 0) {
            $result .= ","
        }
        $result .= $i.'-'.$k;
    }
    echo $result;
    
    0 讨论(0)
  • 2020-12-04 02:40

    I dislike all previous recipes.

    Php is not C and has higher-level ways to deal with this particular problem.

    I will begin from the point where you have an array like this:

    $array = array('john-doe', 'foe-bar', 'oh-yeah');
    

    You can build such an array from the initial one using a loop or array_map() function. Note that I'm using single-quoted strings. This is a micro-optimization if you don't have variable names that need to be substituted.

    Now you need to generate a CSV string from this array, it can be done like this:

    echo implode(',', $array);
    
    0 讨论(0)
  • 2020-12-04 02:45

    Alternatively you can use the rtrim function as:

    $result = '';
    foreach($array as $i=>$k) {
        $result .= $i.'-'.$k.',';
    }
    $result = rtrim($result,',');
    echo $result;
    
    0 讨论(0)
  • 2020-12-04 02:47

    this would do:

    rtrim ($string, ',')
    
    0 讨论(0)
提交回复
热议问题