0

Possible Duplicate:
How to create comma separated list from array in PHP?

I have a Wordpress site, and i use the plugin Magic Fields. To echo the inputs from the plugin I use these code:

<?php 
$my_list = get('startopstilling_test');
foreach($my_list as $element){
echo   $element . ",";

} ?>

The code echo this:

Casillas,Albiol,Xabi Alonso,Kaka,

But i would like to remove the last comma that makes it look like this:

Casillas,Albiol,Xabi Alonso,Kaka

Can anyone help me?

Community
  • 1
  • 1
user2027314
  • 9
  • 1
  • 2
  • 4
    Use [`implode(',', $my_list)`](http://php.net/manual/en/function.implode.php) – NullUserException Jan 30 '13 at 23:24
  • Alternatively, `fputcsv`! The possibilities are endless. – Ry- Jan 30 '13 at 23:25
  • @minitech Doesn't that require a file resource? Or does PHP have something akin to Python's [`StringIO`](http://docs.python.org/2/library/stringio.html)? – NullUserException Jan 30 '13 at 23:27
  • @NullUserException - You could set up a file handle to a stream such as php://temp, and then reset and read the results back into a variable – Mark Baker Jan 30 '13 at 23:30
  • @NullUserException: [I'm just being horrible.](http://codepad.viper-7.com/doqtWO) (Substitute `$stdout` for `STDOUT` for console stuff, 'course.) – Ry- Jan 30 '13 at 23:33

5 Answers5

5

You should use implode instead:

echo implode(',', $my_list);

But if you really want to, you can use rtrim as well.

jeroen
  • 91,079
  • 21
  • 114
  • 132
0

Either use implode, rtrim, or, probably better, use a something like JSON. In its current state, what happens when one of your fields has a comma in it? I suspect things will crash and burn :).

If you do go the route of CSV, you could do it properly with fputcsv:

$han = fopen("php://memory", "rw");
fputcsv($someArray);
fseek($han, 0);
echo stream_get_contents($han);
Corbin
  • 33,060
  • 6
  • 68
  • 78
0

You could do either:

$del = "";
foreach ($my_list as $element)
{
    echo $del . $element;
    $del = ", ";
}

or build it all into a string and then use:

echo rtrim($string, ",");

or even better, just use implode:

echo implode(",", $my_list);
Supericy
  • 5,866
  • 1
  • 21
  • 25
0

You can store it all into one string and then remove the comma

$str="";    
foreach($my_list as $element){
    $str.=$element . ",";}
rtrim($str,',');
echo $str;
Aditsan Kadmus
  • 106
  • 1
  • 1
  • 10
-1

You can concatenate string $elementstr

<?php 
  $my_list = get('startopstilling_test');

  foreach($my_list as $element){
       $elementstr.= $element . ",";
 } 

 ?>

And then

echo rtim($elementstr,',');
v0d1ch
  • 2,738
  • 1
  • 22
  • 27