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

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

    One method is by using substr

    $array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
    
    $output = "";
    foreach($array as $i=>$k)
    {
        $output .= $i.'-'.$k.',';
    }
    
    $output = substr($output, 0, -1);
    
    echo $output;
    

    Another method would be using implode

    $array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
    
    $output = array();
    foreach($array as $i=>$k)
    {
        $output[] = $i.'-'.$k;
    }
    
    echo implode(',', $output);
    

提交回复
热议问题