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

Just a few days back, one of my friend asked me how to break a foreach loop in PHP after a certain number of looping. Well, foreach loop is basically the for loop for arrays. It loops until it reaches the end of the array and keeps on executing the block for each of the array content. So, it is named as foreach Loop. This is the basic structure of a foreach loop in PHP:

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

Here is the complete explanation…

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:

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

Here are the links:


Well it is as simple as that! I hope you have understand the process… Do give your feedback! And if you face any problem, feel free to ask!

7 comments

  1. Julia_Sh

    it was very interesting to read.

    I want to quote your post in my blog. It can?

    And you et an account on Twitter?

  2. Swashata

    Of course that is possible! Just give us a backlink and no problem from us 🙂

  3. Kris

    Dude, this was exactly the help I needed. Thanks for posting this!

  4. Gecko

    Hello,

    don’t you prefer the expression:


    // Initialization

    reset($my_array); // Reset the internal pointer of the array, in case it's not set on the first element
    while (!($count==$max_loop) && list($key, $val)=each($my_array)) {
    echo "The value of $key is $val"; //Print the value of the Array

    $count++; //Increase the value of the count by 1
    }

    I find “breaks” sometimes confusing when it comes to know why a loop ends prematurely (when there’s more than one “break” in a huge loop).

    In this case, you only have to check the condition.

    Have a nice day!

  5. Rick

    I wonder if you could assist with a similar request:

    I’m ultimately trying to read comments from a text file, have one line of the array display for a few seconds, then be replaced by the next and cycle through the entire file.

    I’m able to successfully explode, shuffle, echo or print all lines using foreach, or echo current & next,etc. I’ve tried inserting count routines, but I can’t make it help.

    If I attempt a delay using sleep(2); It calculates the delay of 90 seconds (2 x 45 lines), then prints the entire file at once after the 90 second delay. I’ve tried inserting count routines, but I can’t make it help.

    Any assistance is greatly appreciated.

    Here is the working part of the code I currently have:

    <?
    $file = "comments.txt";
    $f = fopen($file, "r");
    $contents = fread ($f,filesize ($file));
    $delimiter = "#";
    $split = explode($delimiter, $contents);

    shuffle ($split);

    foreach ($split as $quote)

    echo " $quote “;

    fclose($f);
    ?>

  6. Dmitry

    Thanks a lot for the tutorial. It was very helpfull for php beginner like myself.

  7. Dario

    Thank you for this short and extremely useful tutorial, works like a charm!

Comments are closed.