Note that there are some explanatory texts on larger screens.

plurals
  1. POforeach statement forcing while/for to loop too many times
    text
    copied!<p>I have a <code>while/for</code> loop with a <code>foreach</code> loop inside. Reading the code will make it self explanatory as to what I am trying to achieve in terms of logic. </p> <p>In layman's terms, I am trying to create a calendar in PHP. The <code>foreach</code> statement creates 35 cells, for the calendar interface, 4 weeks, 7 days, 5 x 7 = 35. </p> <p>The <code>while</code> loop has taken the number of days in April (30) and trying to each the range 1-30 in each cell. </p> <p>However, when implementing the code below, each number gets iterated 30 times. </p> <pre><code>$i = 1; while ($i &lt;= 30){ foreach ($this-&gt;cells as $cells){ foreach ($cells as $key =&gt; $object){ echo "&lt;td&gt;" . $i . "&lt;/td&gt;"; if($object % 7 == 0){ echo "&lt;/tr&gt;&lt;tr&gt;"; } } } $i++; } </code></pre> <p>I tried this:</p> <pre><code>$i = 1; while ($i &lt;= 30){ foreach ($this-&gt;cells as $cells){ foreach ($cells as $key =&gt; $object){ echo "&lt;td&gt;" . $i . "&lt;/td&gt;"; $i++; if($object % 7 == 0){ echo "&lt;/tr&gt;&lt;tr&gt;"; } } } } </code></pre> <p>Which instead of outputting 1-30 many times each, it outputs 1-35, when I only want 1-30.</p> <p>I have tried a for loop with the result it prints many of each number. For loop code:</p> <pre><code>for ($i = 1; $i &lt;= 30; $i++){ foreach ($this-&gt;cells as $cells){ foreach ($cells as $key =&gt; $object){ echo "&lt;td&gt;" . $i . "&lt;/td&gt;"; if($object % 7 == 0){ echo "&lt;/tr&gt;&lt;tr&gt;"; } } } } </code></pre> <p><code>$this-&gt;cells</code> is a range 1-35 in an array </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload