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 thi开发者_开发问答s adds FOUR LINES OF CODE for something so simple...
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'
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() ? ',' : '';
}
echo implode(",", $list);
without using foreach needed
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(',')
if I get you right, you can use the implode function. This does the job for you.
BR,
TJ
Why not:
echo implode(",", $list);
?
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);
精彩评论