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

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

    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 "
    w: ".$w."
    ";// test text //echo "x: ".$x."
    ";// test text if($w == $x && $w != 0 ) { echo ", "; } echo $value; $x++; }

提交回复
热议问题