Home » PHP » PHP Examples

How to break a foreach loop in PHP?

PHP | Using break in a foreach loop: In this article, we are going to learn how to break a foreach loop in PHP programming?
Submitted by Kongnyu Carine, on May 27, 2019

The break is a keyword that is used to stop the execution of a process after a certain number or after meeting up with particular criteria and transfers the control of the program execution to the next statement written just after the loop body.

In this article, we will learn how to break foreach loop? To break a foreach loop means we are going to stop the looping of an array without it necessarily looping to the last elements because we got what is needed at the moment.

Example 1:

Here, we have an array of the names and breaking the loop execution when a specified string found.

1) PHP code to demonstrate example of break in a foreach loop

<?php
    // 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;
    }
?>

Output

joe
liz
dan

Example 2:

Let's see how to use the break foreach using an associative array that contains the names and ages to display names and age of 2 members of the array?

2) PHP code to use break in a foreach loop with an associative array

<?php
    //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
        //display
        printf("%s is  %d years old<br>", $key, $value);
        //stop when $count equals $end
        if ($count == $end) break;
    }
?>

Output

joe is 12 years old
liz is 13 years old

In this example, we have defined a $count variable to count the number of loops and compare with the $end variable. The $end variable can be any number, it all depends on the number of iterations we need.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.