Siddhu
Siddhu

Reputation: 241

How to break foreach loop or for loop into 10 records

Suppose I have 56 records in my database. I'm using a FOR LOOP to display them.
I want to append div after 10 records every time.

 <?php
        $a = 56;
        for($i=0;$i<$a;$i++){
            echo "<div>";
            echo $i."</br>";
            echo "</div>";
        }
 ?>

output:

<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>
...
<div>56</div>

I want to append <div> after 10 records each time

  <div>
    0
    1
    2
    .
    9
   </div>
   <div>
    10
    11
    .
    19
   </div>
    .
    .
   <div>
    51
    52
    .
    .
    56
   </div>

Upvotes: 1

Views: 1181

Answers (2)

Dekel
Dekel

Reputation: 62556

You can use the modulus operator for that.

<?php
$a = 56;
echo "<div>";
for($i=0;$i<$a;$i++){
    echo $i . "<br />";

    if (($i+1) % 10 == 0) {
        echo "</div><div>";
    }
}
echo "</div>";
?>

Note that if the number of loops is unknown - it's possible that $a will be 9, and your output will be:

<div>
    0
    ...
    9
</div><div>
</div>

If you want to prevent the duplicate of the close-open div in case of exact division, you can change your code to:

<?php
$a = 56;
echo "<div>";
for($i=0;$i<$a;$i++){
    echo $i . "<br />";

    if (($i+1) != $a && ($i+1) % 10 == 0) {
        echo "</div><div>";
    }
}
echo "</div>";
?>

Upvotes: 5

void
void

Reputation: 36703

You need to append the opening and the closing divs based on some condition which primarily are

  1. If it is the first iteration
  2. If it is the tenth iteration
  3. If it is the last iteration

Here is a sample code:

$a = 56;
for ($i = 0; $i < $a; $i++) {

  // If it is the first iteration, echo a opening div
  if ($i == 0)
    echo "<div>";

  // If it is a tenth iteration but not the last one then append a closing and a opening div
  if ($i != 0 && $i % 10 == 0 && $i != $a - 1)
    echo "</div><div>";

  echo $i.
  "<br>";

  // If it is the last iteration, append a closing div
  if ($i == $a - 1)
    echo "</div>";
}

Upvotes: 2

Related Questions