How to break a foreach loop in PHP?

PHP Using break in a foreach circle: In this article, we will figure out how to break a foreach circle in PHP programming?

The break is a catchphrase that is utilized to stop the execution of a procedure after a specific number or in the wake of meeting up with specific criteria and moves the control of the program execution to the following proclamation composed soon after the circle body.

Right now, will figure out how to break foreach circle? To break a foreach circle implies we are going to stop the circling of a cluster without it fundamentally circling to the last components since we got what is required right now.

Example 1:

Here, we have a variety of the names and breaking the circle execution when a predefined string found.

1) PHP code to show an example of a break in a foreach circle

    // array defination
    $names = array("joe", "liz", "dan", "kelly", "joy", "max");
    // foreach loop
    foreach ($names as $name) {
        //  display of the loop
        echo $name . '<br>';
        // stop when name is equal to dan
        if ($name == 'dan') break;



Example 2:

We should perceive how to utilize the break foreach utilizing a cooperative cluster that contains the names and ages to show names and age of 2 individuals from the exhibit?

2) PHP code to utilize break in a foreach circle with an affiliated cluster

    //array definition
    $members = array("joe" => "12", "liz" => "13", "sam" => "14", "ben" => "15");
    //variables to count
    $count = 0;
    //number f display or loop
    $end = 2;
    foreach ($members as $key => $value) {
        $count++; // increment the counter
        printf("%s is  %d years old<br>", $key, $value);
        //stop when $count equals $end
        if ($count == $end) break;


joe is 12 years old
liz is 13 years old

Right now, have characterized a $count variable to check the number of circles and contrast and the $end variable. The $end variable can be any number, everything relies upon the quantity of emphasis we need.

Leave a Comment

error: Alert: Content is protected!!