Creating a comma separated list 2

For years, whenever I have to create a comma separated list from an array I have been writing code that looks vaguely like this.

$first = true;
foreach($arr as $m) {

if ($first) {
$first = false;
}
else {
echo ",";
}
echo $m;
}

I’ve had it. There has to be a cleaner way than using $first to skip the comma on the first value. What am I doing wrong?

2 thoughts on “Creating a comma separated list

  1. MakerBlock Oct 15, 2011 2:10 am

    Assuming you’re using PHP, here’s what I would do:
    ***
    $string = implode(“,”, $array);
    echo $string;
    ***
    Most languages have some variation of PHP’s implode/explode functions.
    Good luck!
    MakerBlock

  2. ben Oct 15, 2011 11:56 am

    Thanks. A lot of people suggested join() as well on twitter. Best answer I got was taking the string and using chop($string, “,”)

    That works the best, because many times I’m reading from objects or arrays of objects.

Comments are closed.