Search for the last foreach () loop entry, invalid

I scroll through my array to print article names:

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

This will obviously lead to something like

 Apple, Banana, Mango, 

But I am looking for:

 Apple, Banana, Mango 

I tried several implode statements as follows:

 <?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 them work for me. How can this be done correctly? Thanks for the tips!

+4
source share
5 answers

You can use foreach to add article names to the array, and then implode() for 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 ?> 
+6
source

it’s much easier to check your first loop iteration, a comma in front of the text and leave that comma in the first iteration:

 <?php if ($articles) { $firstiteration = true: foreach($articles as $article) { if(!$firstiteration){ echo ", "; } $firstiteration = false; echo $article->name; } // end foreach article } // end if has articles ?> 

another (more beautiful in my version) would be possible to override the _toSting () method of your article class:

 ... function __toString(){ return $this->name; } ... 

and just echo implode(", ",$articles)

+6
source

This is the best way to do what you want:

 <?php $string = ''; if ($articles) { foreach($articles as $article) { $string .= $article->name.", "; } } $string = substr($string, 0, -2); echo $string; ?> 
+3
source

PHP has many good array functions, and it screams for one of them.

 $namesArray = array_map(function($x){return $x->name;}, $articles); $string = implode(',' $namesArray); 

OR

 $first = true; array_walk(function($x) use (&$first) { if(!$first) {echo ', ';} else{$first = false;} echo $x->name; }, $articles); 

I also like this answer with the __toString function, but I wanted to show these array functions because I think they are often underused in favor of or unnecessary foreach loops.

0
source

You can remove the last comma and space using the trim function. This is the easiest way.

 <?php if ($articles) { foreach($articles as $article) { echo trim(implode(", ", $article->name), ', '); } } ?> 
0
source

Source: https://habr.com/ru/post/1332652/


All Articles