1

This might actually be a css question but I'm hoping not because I'd like this to work in IE.

I have the following loop:

<?php 
  if ($category)
{
     foreach($category as $item)
         {
               echo $item['name'];
               echo ", ";
         }
} ?>

Which should output

item, item, item, item,

The only thing is...I'd like to NOT have a comma after the last item. Is there any way to do this within a loop?

1
  • 2
    echo if ($category) is wrong btw. Just if ($category). Commented Dec 10, 2010 at 22:50

8 Answers 8

7

Well to keep your code how it is, you could add a counter, and skip the last one.

<?php 
if ($category) {
     $counter = 0;
     foreach($category as $item)
         {
               $counter++;
               echo $item['name'];
               if ($counter < count($category)) {
                   echo ", ";
               }
         }
}
?>

Or you can do it much, much, quicker:

<?php echo implode(", ", array_map(create_function('$item', 'return $item["name"];'), $category)); ?>
Sign up to request clarification or add additional context in comments.

7 Comments

+1 for implode (but your code has some error regarding quotes). Better is to cache the value of count() (I think).
Why the create_function? implode seems to do what the OP wants without all that junk...
@Billy ONeal: that's what I thought, then I realized it's because it has to be $item['name'], not just $item.
@Felix King: Thanks for that Felix. I used the single quotes from the example given on the key, not paying attention to the fact I was already in single quotes. A common issue when using create_function() for me, as I tend to use single quotes for keys.
@Billy ONeal: As @Jonah Bron says, there is the need to access a sub-component, hence the map. Accessing a particular component of an array is so common, it would be nice if there was a built-in map function that did that.
|
4

Don't echo immediately but save your output into a variable that you can trim.

<?php 
if ($category) {
    $output = '';
    foreach($category as $item) {
           $output .= $item['name'];
           $output .= ", ";
    }
    echo rtrim($output, ', ');
} 
?>

3 Comments

Nice, using rtrim(), clearer than the preg_replace() and substr() methods.
Actually substr() is much faster because it doesn't have to know anything. All it has to know it's given (a string and 2 numbers). rtrim() has to search. preg_replace is just crazy
@Rudie: I never said faster, I said clearer, which in the case of the microseconds that operation takes, is most likely more important in the code.
2

The implode solution is the simplest, but you asked for a loop. This method avoids putting an extra conditional in the loop, and therefore should be somewhat more efficient. Basically, instead of doing something different for the last item, you do something different for the first item.

$myArray = array(); //Fill with whatever
$result = $myArray[0];
for ($idx = 1; $idx < count($myArray); $idx += 1)
{
    $result .= ', ' . $myArray[$idx];
}

EDIT: After realizing you want $item['name'] instead of just $item:

$myArray = array(); //Fill with whatever
$result = $myArray[0]['name'];
for ($idx = 1; $idx < count($myArray); $idx += 1)
{
    $result .= ', ' . $myArray[$idx]['name'];
}

1 Comment

Oops, needs to be for ($idx = 1; $idx < count($myArray); $idx += 1).
1

As lovely as foreach is,...

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

...for is sometimes necessary.

3 Comments

A for isn't necessary here. See Orbling's answer. In fact, a loop isn't necessary at all in this case.
@Treeface: The OP specifically asked "Is there any way to do this within a loop?"
@Billy ONeal: Yes, but he probably didn't really mean " it must be in a loop ".
1

Assuming $category is an array, you can use implode to get what you want:

Edit: Missed the $categories['name'] part, this should work:

<?php implode(", ", array_keys($category, 'name')); ?>

4 Comments

That would work well, but he needs to output $item['name'], not just $item.
I think you misunderstood what array_keys does. It won't give you the value of $item['name']. Also note that $categories is at least a 2-dimensional array. It is an arra if items and each item is an array that contains at least the entry name.
@galador That use of array_keys() is quite cool, but 'name' is in the sub-array, not the top-level.
@Orbling: Even if it was in top-level, array_keys works differently: array_keys($category, 'name') will give you all the keys of the elements in $category with the value name. So e.g. applied to array('name', 'foo', 'bar', 'name') it would return array(0, 3).
1

The standard solution to the "last comma" problem is to put items into an array and then implode it:

 $temp = array();
 foreach($category as $item)
    $temp[] =  $item['name'];
 echo implode(', ', $temp);

If you want this more generic, you can also write a function that picks ("plucks") a specific field out of each subarray:

  function array_pluck($ary, $key) {
     $r = array();
     foreach($ary as $item)
         $r[] = $item[$key];
     return $r;
  }

and then just

  echo implode(', ', array_pluck($category, 'name'));

1 Comment

That's a good name for the function I was describing as required in PHP in the comments to my answer. Hence why I use the map. Good though. +1
0

Or you could check for the last key:

end($category);
$lastkey = key($category);
foreach ( $category AS $key => $item ) {
  echo $item['name'];
  if ( $lastkey != $key ) {
    echo ', ';
  }
}

Comments

0

And another option:

<?php 
$out = "";

foreach ($category as $item)
    {
    $out .= $item['name']. ", ";
    }

$out = preg_replace("/(.*), $/", "$1", $out);
echo $out;
?>

6 Comments

Was the preg_replace really all that much easier than substr($out, 0, -2)?
Oops, needs to be $out = preg_replace("/(.*), /", '$1', $out);. The other solutions seem more efficient anyway though... plus substr would probably be better than regex.
@Billy ONeal: yeah, because I never remember the params of substr :) Anyway it will be really rare to find an instance in which you'll find an appreciable difference between the two.
@Billy ONeal, @Jonah Bron: The regexp is many times clearer than the substr(), though is in need of a $. A much clearer regexp in this instance would be preg_replace("/, $/", "", $out).
Actually putting the comma before the value and than using substr($out, 2) is even faster
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.