Creating a comma separated list

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?


Comments

2 responses to “Creating a comma separated list”

  1. 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. 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.