JoshuaDavid
JoshuaDavid

Reputation: 9519

PHP/JS: Removing final comma in a delimited list

What is the best, most concise coding practice for eliminating the final comma when generating a comma-delimted list in a typical for loop? This comes up ALL THE TIME and I cannot stand writing so many extra lines of code for something so simple... there must be a better technique/pattern.

foreach ($list as $item)
{
    echo "'".$item . "',";
}

What is the best way (using PHP and/or JS) to make the above code produce a comma everywhere but the last iteration?

Right now I am doing something like this:

$total = count($images);
$i=0;
foreach ($list as $item)
{
    $i++;
    echo "'".$item."'";
    if ($i<$total) echo ',';
}

But this adds FOUR LINES OF CODE for something so simple...

Upvotes: 0

Views: 233

Answers (7)

hakre
hakre

Reputation: 197795

In case you didn't simplified the code example:

echo implode(',', $list);

does it (see also implode PHP Manual ).

If there is more code within the foreach loop you need to keep track whether or not you're on the last element and deal with the situation:

$count = count($list);
$current = 0;
foreach ($list as $item)
{
    $current++;
    $notLast = $current !== $count;
    echo $item;
    if ($notLast) echo ',';
}

Edit: you added a similar code to the question after I answered this, so if that is too burdensome for your coding fingers and especially (and understandable) you don't want to repeat such code all day long the same, you need to encapsulate it for re-use. One solution is to implement this within a re-useable iterator:

$list = array('a', 'b', 'c');

class PositionKnowingIterator implements iterator
{
    /**
     * @var iterator 
     */
    private $inner;
    private $count;
    private $index;
    public function __construct(array $list) {
        // NOTE: implement more iterators / objects to deal with in here
        //       if you like. This constructor limits it to arrays but
        //       more is possible.
        $this->count = count($list);
        $this->inner = new ArrayIterator($list);
    }
    /* SPL iterator implementation */
    public function current() {
        return $this->inner->current();
    }
    public function next() {
        $this->index++;
        $this->inner->next();
    }
    public function key() {
        $this->inner->key();
    }
    public function rewind() {
        $this->index = 1;
        $this->inner->rewind();
    }
    public function valid() {
        return $this->inner->valid();
    }
    /* Position Knowing */
    public function isLast() {
        return $this->index === $this->count;
    }
    public function notLast() {
        return !$this->isLast();
    }
    public function isFirst() {
        return $this->index === 1;
    }
    public function notFirst() {
        return !$this->isFirst();
    }
    public function isInside() {
        return $this->notFirst() && $this->notLast();
    }
}


foreach($iterator = new PositionKnowingIterator($list) as $item)
{
    echo "'".$item."'", $iterator->notLast() ? ',' : '';
}

Upvotes: 4

Kitta
Kitta

Reputation: 324

The common used practice: using 'join' function or its analog. This function exists almost in every language, so it's most simple, clear and environment independent approach.

echo join(", ", $list);

Upvotes: 0

salathe
salathe

Reputation: 51950

The Standard PHP Library (SPL) offers a handy class, CachingIterator that can be used to see if there are any more items to be iterated over. The following may not be as concise as you would like but it is flexible (i.e. can be used for far more than just arrays).

$array = range('a', 'g');
$cache = new CachingIterator(new ArrayIterator($array));
foreach ($cache as $item) {
    echo "'$item'";
    if ($cache->hasNext()) {
        echo ',';
    }
}

The above example outputs

'a','b','c','d','e','f','g'

Upvotes: 5

WASD42
WASD42

Reputation: 2379

User implode() function to achieve this. Sometimes it's also necessary to put something around, for example, to quote SQL fields' values:

$fields = '"' . join('", "', $values) . '"';

And for JavaScript use Array.join() method (W3C):

var implodedString = someArray.join(',')

Upvotes: 1

guido
guido

Reputation: 19194

Why not:

echo implode(",", $list);

?

Upvotes: 1

TerenceJackson
TerenceJackson

Reputation: 1786

if I get you right, you can use the implode function. This does the job for you.

BR,

TJ

Upvotes: 1

genesis
genesis

Reputation: 50976

echo implode(",", $list);

without using foreach needed

Upvotes: 2

Related Questions