Counter to add seperator on foreach

I have an foreach to add terms to a post on WordPress Which is working great. Code below:

<h3>
<?php foreach($terms as $term) {?>
    <?php echo $term->name;?>
<?php } ?>
</h3>

However I need to add a counter so that if there is more than one term in the <h3> it adds a / between them. For instance:

Read More
<h3>Term Name</h3>
<h3>Term Name / Term Name / Term Name</h3>

This is the code I have so far however its not working.

        <?php
        $i = 1;
        foreach($terms as $term) {

        if($i == 1){ 
         echo ' / '.$term->name;
        } else { 
            echo $term->name;
        }   
        $i++;  
        } ?>

Related posts

4 comments

  1. You don’t need to use a counter. Just put each $term->name in to an array, and implode it:

    echo implode(' / ', array_map(function($term) { return $term->name; }, $terms));

    Here’s a demo

  2. Please try below code.

    <?php $terms = array_values($terms); 
    if( sizeof($terms) > 1){ ?>
            <h3><?php echo  implode(' / ', array_map(function($term) { return $term->name; }, $terms)); ?></h3>
    <?php }else{ $term = $terms[0]; ?>
                <h3>echo $term->name;</h3>
    <?php } ?>
    
  3. <?php
        $i = 1;
        foreach($terms as $term) {  
            if($i > 1) { 
                echo ' / '.$term->name;
            } else { 
                echo $term->name;
                $i++; 
            } 
        }
    ?>
    
  4. Here is the working solution 🙂

     <?php 
        $terms = array("Term One","Term Two","Term Three","Term Four");
        $i = 1;
        $result="";
        foreach($terms as $term)
        {
            if($i==1)
             {
                $result=$result.$term.' ';
                $i++;   
              } 
            else
                {               
                    $result=$result."/".' ';
                    $result=$result.$term.' ';
                }       
    
        }
       echo $result;    
     ?>
    

Comments are closed.