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:

<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>

Revisions

No comments yet.

Leave a Reply