michaelmcgurk
michaelmcgurk

Reputation: 6509

Break while loop every 3 iterations

I am using this PHP to generate a list from 0-9.

$counter = 0; 
WHILE ($counter < 10) 
{ 
  print "counter is now " . $counter . "<br>"; 
  $counter++; 
}

I'd like to change how this works. Every 3rd iteration, I'd like to wrap my printed text in a <div> if possible.

So eventually my outputted code would be:

<div>
counter is now 0
counter is now 1
counter is now 2
</div>
<div>
counter is now 3
counter is now 4
counter is now 5
</div>
<div>
counter is now 6
counter is now 7
counter is now 8
</div>
<div>
counter is now 9
</div>

Upvotes: 0

Views: 2499

Answers (5)

pankijs
pankijs

Reputation: 6893

I have found that best failsafe approach for this kind of task would be group all data (in this case all 10 your printed strings) in array, than split this array in chunks http://php.net/manual/en/function.array-chunk.php, and then you can work with this new array, because it is divided in chunks, where each chunk is not greater than for example 3. but your output won't fail because modals will only work if your total count of elements modal is 0, in this case 10 elements will fail, because in last loop modal statement won't work.

this will add failsafe when there isn't total elements that divides with 3.

$counter = 0; 
$arr = array();
WHILE ($counter < 10) 
{ 
  $arr[] =  "counter is now " . $counter . "<br>"; 
  $counter++; 
}

$arr = array_chunk($arr, 3);
foreach ($arr as $chunk) {
    //wrap each chunk into div
    echo "<div>"
    foreach ($chunk as $string) {
        //print your string here
     }
    echo "</div>"
}

Upvotes: 0

Nofar Eliasi
Nofar Eliasi

Reputation: 109

i don't know php but i think the logic is the same :

$counter2 =0; //count to 10
$stopIteration =10;

WHILE($counter2<$stopIteration){ 
    print "<div>";
    $counter1 =0; //count to 3
    WHILE($counter1<3){
        print "counter is now".$counter2."<br>";
        $counter1++;
        $counter2++;
    }
    print "</div>"; 
} 

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

With modulus operator you can split your output every 3 iterations but you still need to check for limit values that could generate empty div blocks

<?php

$counter = 0; 
$limit = 10;

print "<div>\n";

while ($counter < $limit) { 
  print "counter is now " . $counter . "<br>\n"; 

  if (++$counter % 3 === 0 && $counter < $limit) {
    print "</div>\n<div>\n";

  }
}
print "</div>\n";

Upvotes: 1

ala_747
ala_747

Reputation: 611

Try with:

$counter = 0;
$block_count = 0;
echo "<div>";
while ($counter < 10) {
if ($block_count === 3) {
    echo "</div><div>";
    $block_count = 0;
}
  echo "counter is now " . $counter . "<br>";
  $block_count++;
  $counter++; 
}
echo "</div>";

Upvotes: 0

Machavity
Machavity

Reputation: 31624

Use a modulus to do it

while($counter < 10) {
   if($counter % 3 == 0) {
       //Do something for the third row
   }
   $counter++;
}

Upvotes: 1

Related Questions