deathride
deathride

Reputation: 28

How to trim an output of a foreach over an array

Ive got an array of Wordpress-Categories. What I want, is to output their names, seperated with a comma. - like this:

category1, category2, category3, category4, category5, ...

I tried this foreach loop:

foreach ($category as $cat){
  $catList = $cat->name.', ';
  echo $catList ;
}

But the output looks like this: category1, category2, category3,

As you can see, there is a comma at the end, which I dont want.

How would this work?

Upvotes: 0

Views: 445

Answers (4)

Friedrich
Friedrich

Reputation: 2290

My solution would look like this: (untested)

for ($i = 0; $i < count($category); $i++) {
  echo $category[$i]->name;
  echo ($i - 1 < count($category)) ? ', ' : '';
}

This will only output the commas after all elements except when $i - 1 is less than the length of the category array. That means after all elements, except the last one.

Upvotes: 0

Yazan
Yazan

Reputation: 6082

you are doing it correct, but you don't need to use it inside the loop, just one time after the for loop ends

for(.....){

}
$catlist= rtrim($catlist, ', ');

Upvotes: 0

user3901786
user3901786

Reputation: 103

Here is a simple way, just off the top of my head:

$firstitem=1;
foreach ($category as $cat) {
    if ($firstitem == 1) {
        $firstitem = 0;
    } else {
        $catList .= ', ';
    }
    $catList .= $cat->name;
}
echo $catList ;

Of course, you could just echo the comma and name values without saving them. I did it this way in case you wanted to do something else with the catList string.

Upvotes: 1

ocirocir
ocirocir

Reputation: 4058

One and simple built-in function:

$catList = implode(", ", $category);

Upvotes: 1

Related Questions