Loop PHP counter with a foreach

0

I have this code that generates a list of the best rated posts and works perfectly.

echo "<div class='col-md-10'>";
    echo '<ul>';
    foreach ($posts as $post)
    {
       echo "<li class='f$post->ID'><a href='".get_permalink($post->ID)."'>".$post->post_title."</a>";
       if($sr)
       {
           $best = get_option('kksr_stars');
           echo " <span class='toprat' style='font-size:10px;'>".$post->ratings."</span>";
       }
       echo "</li>";
    }
    echo '</ul>';
    echo "</div>";

This generates something like this:

Title of a post 10.0 points

Title of another post 8.0points ...

I would like to create inside the loop a counter that was changing so that each time it was executed it will show the position next . Example:

1st Title of a post 10.0 points

2nd Title of another post 8.0points ...

I have the loops a bit rusty and I do not do more than load the code, if someone can guide me I appreciate it.

    
asked by PC Solución 27.09.2018 в 04:09
source

1 answer

2

Try with:

echo "<div class='col-md-10'>";
echo '<ul>';
foreach ($posts as $position => $post)
{
   echo "<li class='f$post->ID'><a href='".get_permalink($post->ID)."'>".($position+1)."º ".$post->post_title."</a>";
   if($sr)
   {
       $best = get_option('kksr_stars');
       echo " <span class='toprat' style='font-size:10px;'>".$post->ratings."</span>";
   }
   echo "</li>";
}
echo '</ul>';
echo "</div>";

In this way the foreach returns the index of each element of the array. Just add one and print it on screen.

    
answered by 27.09.2018 / 04:34
source