Skip to content
Advertisement

Using for loop data to for 10 rows at a time

I could not find an answer to this question or I completely missed the answer, what I am doing is looping from a database, just a number value, this variable $competition[‘competition_number_of_tickets’] could be for example 200.

                  <?php
                  $counter = 0;
                  for ($i = 1; $competition['competition_number_of_tickets'] >= $i; $i++) {
                    if ($i % 10 === 0) {
                        echo "<button type="button" class="btn btn-primary">{$i}</button>";       
                    } else {
                        echo "<hr />"; 
                    }
                  }               
                  ?>

The way my code is now, each button lists 1 after each other, what I’m trying to do is have 10 buttons on each row to make it look nicer, I know that my code is not working as expected could anyone explain what I’m doing wrong? I’m not great with maths.

Advertisement

Answer

Your loop should compare $i to the total, as in

for ($i = 1; $i <= $competition['competition_number_of_tickets']; $i++)

Then, your modulus will fire every time the counter gets to a multiple of 10, but the way you have it now (which is reversed from how you want it) it will show a button only when the counter gets to a multiple of 10. Even if you had that right, it would still ignore ignore the 10th button. Your if statement should look more like

echo "<button type="button" class="btn btn-primary">{$i}</button>";       
if ($i % 10 === 0) echo "<hr />"; 
               
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement