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> <pre>$count = 0; //First we set the count to be zeo</pre> <pre>echo "<h2> Here goes the values</h2>";</pre> <pre>foreach($my_array as $key => $val) {</pre> <pre> echo "The value of $key is $val<br/>"; //Print the value of the Array</pre> <pre> $count++; //Increase the value of the count by 1</pre> <pre> if($count==$max_loop) break; //Break the loop is count is equal to the max_loop</pre> <pre>}</pre>
Revisions
- April 19, 2013 @ 16:07:41 [Current Revision] by PeterLugg
- April 19, 2013 @ 16:06:54 by PeterLugg
No comments yet.