Create a comma-separated string from a single column of an array of objects

前端 未结 14 1414
醉话见心
醉话见心 2020-11-30 07:36

I\'m using a foreach loop to echo out some values from my database, I need to strip the last comma from the last loop if that makes sense.

My loop is just simple, as

14条回答
  •  时光说笑
    2020-11-30 08:04

    I've been having the same issue with this similar problem recently. I fixed it by using an increment variable $i, initializing it to 0, then having it increment inside the foreach loop. Within that loop place an if, else, with the echo statement including a comma if the $i counter is less than the sizeof() operator of your array/variable.

    I don't know if this would fix your issue per se, but it helped me with mine. I realize this question is years-old, but hopefully this will help someone else. I'm fairly new to PHP so I didn't quite understand a lot of the Answers that were given before me, though they were quite insightful, particularly the implode one.

    $i=0;
    foreach ($results as $result) {
        $i++;
        if(sizeof($results) > $i) {
            echo $result . ", ";
        } else {
            echo $result;
        }
    }
    

提交回复
热议问题