Jako
Jako

Reputation: 4901

Counter inside while loop every X times increase

I'm not really sure how to work this question, but I currently have a while loop outputting <li></li>.

Let's say that there are 35 rows and I want the counter to increase every five times.

So the output would be something like this.

 - 1 Name
 - 1 Name
 - 1 Name
 - 1 Name
 - 1 Name
 - 2 Name
 - 2 Name
 - 2 Name
 - 2 Name
 - 2 Name
 - 3 Name
 - 3 Name
 - 3 Name
 - 3 Name
 - 3 Name
 - 4 Name and so on...

I've tried counting throughout the loop and comparing the number to see if it was less than five and if not then increasing it, but I know that's not correct. Just can't seem to figure out the best solution.

 while ($stmt->fetch()) {

          $HTML .= "<li data-id='$id' data-name='$name'>$count Name</li>";              
    }

To try to make this clearer...basically I would like to have a counter variable running. Starting at 1, but every fifth time through the while loop, I would like to increase this count variable by one.

Upvotes: 0

Views: 2868

Answers (4)

Jared Farrish
Jared Farrish

Reputation: 49188

You could use array_fill() (psuedo code):

<?php

$li = "<li>Item</li>";

$row = array_fill(0, 5, $li);

$list = array_fill(0, 35, $row);

print_r($list);

?>

http://codepad.org/ETCv3GBK

As in:

$count = 0;

while ($stmt->fetch() && $count++) {
    $HTML .= implode('', array_fill(0, 5, "<li data-id='$id' data-name='$name'>$count Name</li>"));
}

Another demo (ignite.io may not be working on save, though):

https://ignite.io/code/514a9bf5ec221ee821000005

Upvotes: 1

ElefantPhace
ElefantPhace

Reputation: 3814

for($i=1; $i <= 20; $i++){
    $array[] = "Name " . $i;
}

$count = 1;
$output = 1;
for($i=0; $i < 20; $i++){
    if($count++ < 5)
        echo $output . ". " . $array[$i] . "<BR>";
    else{
        $count = 1;
        echo $output++ . ". " . $array[$i] . "<BR>";
    }
}

returns

  1. Name 1
  2. Name 2
  3. Name 3
  4. Name 4
  5. Name 5
  6. Name 6
  7. Name 7
  8. Name 8
  9. Name 9
  10. Name 10
  11. Name 11
  12. Name 12
  13. Name 13
  14. Name 14
  15. Name 15
  16. Name 16
  17. Name 17
  18. Name 18
  19. Name 19
  20. Name 20

Upvotes: 0

Mark Parnell
Mark Parnell

Reputation: 9215

$count = $rows = 0;
while ($stmt->fetch()) {
    if ($rows % 5 == 0)
        $count++;
    $rows++;
    $HTML .= "<li data-id='$id' data-name='$name'>$count Name</li>";              
}

Upvotes: 4

Praveen kalal
Praveen kalal

Reputation: 2129

$i=1
while ($stmt->fetch()) {

       if($i%5==0){
          $HTML .= "<li data-id='$id' data-name='$name'>$count Name</li>";              
       }
$i++;
    }

Upvotes: -1

Related Questions