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?

5
  • 4
    Use implode(',', $my_list) Commented Jan 30, 2013 at 23:24
  • Alternatively, fputcsv! The possibilities are endless. Commented Jan 30, 2013 at 23:25
  • @minitech Doesn't that require a file resource? Or does PHP have something akin to Python's StringIO? Commented Jan 30, 2013 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 Commented Jan 30, 2013 at 23:30
  • @NullUserException: I'm just being horrible. (Substitute $stdout for STDOUT for console stuff, 'course.) Commented Jan 30, 2013 at 23:33

5 Answers 5

5

You should use implode instead:

echo implode(',', $my_list);

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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);

Comments

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;

Comments

-1

You can concatenate string $elementstr

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

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

 ?>

And then

echo rtim($elementstr,',');

1 Comment

but faster solution would be to just do implode()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.