Tuesday 14 August 2018

How to break a foreach loop in PHP after a certain number

<?php
foreach($my_array as $key => $value) {
    //Code to execute
}
?>
Obviously we already have set $my_array as an array with definite number of elements. The loop continues to execute on each of the array element until it reaches the end of the array. For example, the following is a code to print all the elements of the an Array…
<?php
foreach($my_array as $key => $value) {
    echo "The value of $key is $value<br/>";
}
?>
Now the question is how to break the foreach loop before the end of the Array… Well, the solution is actually pretty simple! We just have to use an if statement to break the foreach loop. Here is how we are going to do this…

How to break the foreach Loop in PHP
Here is the complete explanation…
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:
$max_loop=5; //This is the desired value of Looping
$count = 0; //First we set the count to be zeo
echo "<h2> Here goes the values</h2>";
foreach($my_array as $key => $val) {
    echo "The value of $key is $val<br/>"; //Print the value of the Array
    $count++; //Increase the value of the count by 1
    if($count==$max_loop) break; //Break the loop is count is equal to the max_loop
}
Obviously you can use PHP’s post or get method to set the $max_loop and loop the array for a user defined time, for production purposes! Just check the Source code of my Online Demo to see how things are set…

0 comments:

Post a Comment