skip to Main Content

I can’t get my head around how to change what is outputed for the last item in a foreach loop in php. I have the code below which renders well, but I want to remove the comma from after the last item that is rendered in the foreach loop.

if(!empty($terms)){
    foreach($terms as $term){
        echo $term->name.', ';
    }
}

How can I modify this to render the last item in the loop without the ', ' bit?

If someone can explain and show me that would be great so I can learn how it works.

4

Answers


  1. Chosen as BEST ANSWER

    I changed my approach here and added a around each item rendered from the foreach loop and then used CSS to add a comma to all but the last-of-type - this way worked more logically for my visual brain ;)


  2. You could use array_column to get all "name" values, and then implode to make one string. Then remains to echo it…

    if(!empty($terms)){
        echo implode(" ", array_column($terms, "name"));
    }
    
    Login or Signup to reply.
  3. You cannot remove the text after you’ve emitted it, obviously.

    So you need to not emit it in the first place.

    One way is to send the separator before each item except the first, instead of after each item except the last, because determining the first item is simpler – and actually can be coded using the separator itself:

    $sep = ''; // '' means it's the first
    foreach($terms as $term){
        echo $sep . $term->name;
        $sep = ', ';
    }
    

    (You do not need the check empty($terms)).

    The above approach is useful if you have more levels of nesting (for example, you have a series of rows that need to be grouped by city, contractor and contract number, and your "separator" is a row of subtotals): instead of $sep you’ll have an array $sep[$nestingLevel], which can hold a fixed separator string or an array of subtotals.

    In the simplest case when you want a straight concatenation of items, you can do this with implode(), that does the same thing:

    print implode(
        ', ',
        // if $terms is an array of strings, just use $terms.
        // if it is an array of arrays, use array_column($terms, KEYNAME_OR_INDEX);
        // but here you have an array of objects, so it's more complicated:
        array_map(
            static fn($term) => $term->name, // Extract $.name
            $terms
        )
    );
    
    Login or Signup to reply.
  4. if(!empty($terms)){
        foreach($terms as $k => $term){
            echo $term->name.($k < count($terms)?',&nbsp;':'');
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search