Reputation: 1235
I'm fairly new to PHP and to get a better understanding of it I'm building a small application where I can add movies into watchlists, see upcoming movies, ...
Right now I'm trying to build a top rated list that lists all the movies a user has added in order from highest to lowest rating.
The syntax I have right now is:
<?php
while($avr = mysql_fetch_array($rating)) {
for ($i=1; $i<5; $i++){ ?>
<li class="movie"><?php echo $i . ' - ' . $avr['title'] . '<div class="movie_rating">' . $avr['vote_avr'] . '</div>'; ?></li>
<?php } } ?>
"$i<5;" in the for-loop is hardcoded at the moment for testing, this will be replaced with a variable.
The problem I have with this is that it counts from 1 to 4 for each "$avr['title']". So it prints each movie title 4 times on my page. I just want the first movie title to be "1", the second "2", etc.
If I place the for-loop outside the while-loop, each movie will be "1".
So my question is, how can I integrate a for-loop within a while-loop that counts up just once for each while-loop value?
Thanks in advance.
Upvotes: 1
Views: 5548
Reputation: 2089
<?php
$i = 1;
while($avr = mysql_fetch_array($rating)) {
if($i < 5) {
?>
<li class="movie"><?php echo $i . ' - ' . $avr['title'] . '<div class="movie_rating">' . $avr['vote_avr'] . '</div>'; ?></li>
<?php $i++; } } ?>
Also you can add else clause
to break the loop
after your desired iterations
Upvotes: 1
Reputation: 13535
You don't need the for loop.
<?php
$i=1;
while($avr = mysql_fetch_array($rating)) {
<li class="movie"><?php echo $i . ' - ' . $avr['title'] . '<div class="movie_rating">' . $avr['vote_avr'] . '</div>'; ?></li>
<?php $i++;
} ?>
Upvotes: 1
Reputation: 23787
You don't need a for loop. You just need a counter variable (I named it $i
here) you increment each time you enter the while loop:
$i = 0;
while($avr = mysql_fetch_array($rating)) {
?>
<li class="movie"><?php echo ++$i . ' - ' . $avr['title'] . '<div class="movie_rating">' . $avr['vote_avr'] . '</div>'; ?></li>
<?php
// Increment & Insert ---------^
}
Upvotes: 4