开发者

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

开发者 https://www.devze.com 2023-01-31 12:31 出处:网络
I loop through my array to print the articles names: <?php if ($articles) { foreach($articles as $article) {

I loop through my array to print the articles names:

<?php
if ($articles) { 
    foreach($articles as $article) { 
        echo $arti开发者_如何学Ccle->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!


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
?>


it's much more easy to check for your first loop-iteration, wrte the comma before your text and leave this comma aout on 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 optionion) possibility would be to override the _toSting()-method of your article-class:

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

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


It is better way to do what you want:

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


PHP has a lot of good array functions, and this 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 really like the above response with the __toString function also, but I wanted to show these array functions because i think they are often underused in favor or unnecessary foreach loops.


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

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

精彩评论

暂无评论...
验证码 换一张
取 消