0

please someone can guide me to write nested loop like this in php for loop

output:

<tr>
1
2
3
4
5
6
</tr>
<tr>
7
8
9
10
11
12
</tr>

for ($a=0; $a < 10; $a++) { 
        echo $a;
    }
2
  • 2
    What issues have you encountered when you attempted to solve this problem? Please update question with explanation. Likely should look at modulo operator. You also should have a td or multiple tds if multiple cells are expected. Commented Sep 28, 2021 at 15:07
  • i am creating table like [123456] [789101112] Commented Sep 28, 2021 at 15:52

1 Answer 1

1

You are probably looking for something like that:

<?php
echo "<table>\n";
echo "  <tr>\n";
foreach (range(1, 12) as $i) {
  if ($i>1 && ($i-1) % 6 == 0) {
    echo "  </tr>\n  <tr>\n";
  }
  echo "    <td>$i</td>\n";
}
echo "  </tr>\n";
echo "</table>\n";

Another approach would be to chunk a given set:

<?php
$set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

echo "<table>\n";
foreach (array_chunk($set, 6) as $chunk) {
  echo "  <tr>\n";
  foreach ($chunk as $number) {
    echo "    <td>$number</td>\n";
  }
  echo "  </tr>\n";
}
echo "</table>\n";

The output obviously is:

<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
  <tr>
    <td>7</td>
    <td>8</td>
    <td>9</td>
    <td>10</td>
    <td>11</td>
    <td>12</td>
  </tr>
</table>
Sign up to request clarification or add additional context in comments.

Comments

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.