Build comma separated string in PHP Loop

后端 未结 4 643
抹茶落季
抹茶落季 2021-01-21 22:36

Hello Guys i need to do this,

I have a common loop

foreach ($stuffs as $stuff) {
echo $stuff;
}

Lets assume $stuff is an \'id\' of a my

相关标签:
4条回答
  • 2021-01-21 22:48

    Should be as simple as:

    $string = implode(",",$stuffs);
    echo $string
    
    0 讨论(0)
  • 2021-01-21 22:57

    This worked in my case (detects if isn't the loop last iteration):

    foreach($array as $key => $val){
        ...
        if($key!==count($array)-1){echo ',';}
    }
    
    0 讨论(0)
  • 2021-01-21 22:59

    If you really wanna have the loop:

    $values = "";
    
    foreach ($stuffs as $stuff) {
        $values != "" && $values .= ",";
        $values .= $stuff;
     }
    
    echo $values;
    

    I suggest using implode, but the loop can really give you more power if you wanna do some further stuff.

    0 讨论(0)
  • 2021-01-21 23:06

    implode should be the tool:

    implode(",", $stuffs);
    

    will return a comma separated list.

    Test

    $myarray=array(1,2,"hello",4,5);
    echo implode(",", $myarray);
    

    returns

    1,2,hello,4,5
    
    0 讨论(0)
提交回复
热议问题