1

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.

0

3 Answers 3

4

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 ---------^
}
Sign up to request clarification or add additional context in comments.

Comments

1

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++;
  } ?>

1 Comment

+1 for helping me, I've accepted bwoebi's answers since his solution is abit shorter. But thanks for taking the time to answer my question.
1
<?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

1 Comment

+1 for helping me, I've accepted bwoebi's answers since his solution is abit shorter. But thanks for taking the time to answer my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.