Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding last entry of foreach() loop, implode not working

I loop through my array to print the articles names:

<?php
if ($articles) { 
    foreach($articles as $article) { 
        echo $article->name.", ";       
    } // end foreach article
} // end if has articles
?>

This will obviously produce something like

Apple, Banana, Mango,

But I am looking for:

Apple, Banana, Mango

I tried some implode statement like this:

<?php
if ($articles) { 
    foreach($articles as $article) { 
        echo implode(", ", $article->name);     
    } // end foreach article
} // end if has articles
?>

or

<?php
if ($articles) { 
    echo implode(", ", $articles->article->name);       
} // end if has articles
?>

None of these are working for me. How can do it right? Thanks for hints!

like image 483
caratage Avatar asked Dec 08 '22 00:12

caratage


1 Answers

You can use foreach to add the article names to an array, then implode() that array of names.

<?php
if ($articles) { 
    $article_names = array();

    foreach($articles as $article) { 
        $article_names[] = $article->name;
    } // end foreach article

    echo implode(', ', $article_names);
} // end if has articles
?>
like image 75
BoltClock Avatar answered Dec 10 '22 12:12

BoltClock