Question

I have a question and answer forum. A user may browse responses to questions and promote them if they wish. The code below outputs the different users that have promoted a given question - the users are in the array '$promoters' that is returned from the line $promoters = Promotion::find_all_promotions_for_response($response->response_id); . The foreach loop then goes through each and outputs them, styles by the css class "promoter list". Problem is this.....if I have one promoter I just want their name outputed (no problem with this). But if I have many I want to put a comma between each name and then none after the last name in the foreach loop. Straightforward problem but I failed to achieve this....I tried to add a count($promoters) line in an elseif condition so that if the array $promoters has more than one value, then it outputs the users fullname and then a comma, but of course the last name also has a comma after it which is wrong. How do you indentify the last iteration in a foreach loop and ask it to do something different with this.....

Many thanks guys...

          <?php 
          $promoters = Promotion::find_all_promotions_for_response($response->response_id);
              if(!empty($promoters)){
              echo "<span class=\"promoted_by\">Promoted by </span>";
              foreach($promoters as $promoter){
              echo "<span class=\"promoter_list\">" . User::full_name($promoter->user_id) . ", </span>";
              } 
              } else {
              echo "";                
              };
           ?>   
Was it helpful?

Solution

<?php 
$promoters = Promotion::find_all_promotions_for_response($response->response_id);
if(!empty($promoters)){
    echo "<span class=\"promoted_by\">Promoted by </span>";
    foreach($promoters as $idx=>$promoter){
        echo "<span class=\"promoter_list\">" . User::full_name($promoter->user_id);
        if($idx < count($promoters) - 1) {
            echo ", ";
        }
        echo "</span>";
    } 
} else {
    echo "";                
}
?>

UPDATE:

This is another way to do it using implode as suggested by @deceze:

<?php 
$promoters = Promotion::find_all_promotions_for_response($response->response_id);
if(!empty($promoters)){
    echo "<span class=\"promoted_by\">Promoted by </span>";
    $htmlParts = array();
    foreach($promoters as $idx=>$promoter){
        $htmlParts[] = "<span class=\"promoter_list\">" . User::full_name($promoter->user_id);
    } 
    echo implode(', </span>', $htmlParts) . '</span>';
} else {
    echo "";                
}
?> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top