Revision 418 is a pre-publication revision. (Viewing current revision instead.)

How to break the foreach Loop in PHP

Basically we are going to use the following algorithm:
  • First we set a variable $count to 0 [Integer Type]
  • Now on each loop of the foreach we increase the value of $count by 1.
  • Just after the increment, inside the foreach loop we check if the value of $count is equal to the desired value of looping. If the value is equal then we just break the loop using break;
Here is the code: [php] <pre>$max_loop=5; //This is the desired value of Looping</pre> &nbsp; <pre>$count = 0; //First we set the count to be zeo</pre> &nbsp; <pre>echo "<h2> Here goes the values</h2>";</pre> &nbsp; <pre>foreach($my_array as $key => $val) {</pre> &nbsp; <pre> echo "The value of $key is $val<br/>"; //Print the value of the Array</pre> &nbsp; <pre> $count++; //Increase the value of the count by 1</pre> &nbsp; <pre> if($count==$max_loop) break; //Break the loop is count is equal to the max_loop</pre> &nbsp; <pre>}</pre> [/php]

Revisions

  • April 19, 2013 @ 16:07:41 [Current Revision] by PeterLugg
  • April 19, 2013 @ 16:06:54 by PeterLugg

Revision Differences

April 19, 2013 @ 16:06:54Current Revision
Content
 Added: Basically we are going to use the following algorithm:
Deleted: Added: <ul>
 Added: <li>First we set a variable <strong> $count </strong>to 0 [<em>Integer Type</em>]</li>
 Added: <li>Now on each loop of the <strong> foreach </strong>we increase the value of <strong>$count< /strong> by 1.</li>
 Added: <li>Just after the increment, inside the <strong> foreach</strong> loop we check if the value of <strong>$count< /strong> is equal to the desired value of looping. If the value is equal then we just break the loop using <strong> break;</strong></li>
 Added: </ul>
 Added: Here is the code:
 Added: [php]
 Added: &lt;pre&gt;$max_loop=5; //This is the desired value of Looping&lt;/pre&gt;
 Added: &amp;nbsp;
 Added: &lt;pre&gt;$count = 0; //First we set the count to be zeo&lt;/pre&gt;
 Added: &amp;nbsp;
 Added: &lt;pre&gt;echo &quot;&lt;h2&gt; Here goes the values&lt;/h2&gt; &quot;;&lt;/pre&gt;
 Added: &amp;nbsp;
 Added: &lt;pre&gt;foreach($my_array as $key =&gt; $val) {&lt;/pre&gt;
 Added: &amp;nbsp;
 Added: &lt;pre&gt; echo &quot;The value of $key is $val&lt;br/&gt;&quot;; //Print the value of the Array&lt;/pre&gt;
 Added: &amp;nbsp;
 Added: &lt;pre&gt; $count++; //Increase the value of the count by 1&lt;/pre&gt;
 Added: &amp;nbsp;
 Added: &lt;pre&gt; if($count==$max_loop) break; //Break the loop is count is equal to the max_loop&lt;/pre&gt;
 Added: &amp;nbsp;
 Added: &lt;pre&gt;}&lt;/pre&gt;
 Added: [/php]

Note: Spaces may be added to comparison text to allow better line wrapping.

No comments yet.

Leave a Reply