Home >Backend Development >PHP Problem >Example of how to terminate or interrupt a loop in PHP

Example of how to terminate or interrupt a loop in PHP

藏色散人
藏色散人Original
2021-08-17 10:16:013274browse

Before introducing this article, I recommend that you read the "PHP Loop" chapter in the PHP manual. Of course, if you are already very familiar with PHP loop statements, then go straight to the topic!

As the title says, this article will introduce to you how to terminate and interrupt the loop in PHP. In fact, this is also the most common interview question in the PHP interview process!

So what if the interviewer asks you: "How to terminate or interrupt a loop in PHP"?

You can answer like this: "You can terminate or interrupt the loop anywhere in PHP by using the break keyword in the loop."

Let’s look directly at an example of terminating the loop:

The PHP code is as follows:

<?php
$months = array(&#39;jan&#39;, &#39;feb&#39;, &#39;mar&#39;, &#39;apr&#39;, &#39;stop&#39;, &#39;may&#39;);
foreach ($months as $month) {
    if ($month == &#39;stop&#39;) {
        break;
    }
    echo "$month<br>";
}

The output result is:

Example of how to terminate or interrupt a loop in PHP

jan
feb
mar
apr

In the above code, we first define an array, then loop through the array values ​​​​through the foreach statement, and then judge through if. If $month is equal to stop, break the loop and it will be directly If all array elements before stop are output, then the elements after stop will naturally not be output.

Here I would like to introduce to you what are the loop statements in PHP?

In PHP, there are the following loop statements:

while statement: As long as the specified condition is true, the code block will be looped;

do...while statement: executed first A code block once, and then the loop is repeated as long as the specified condition is true;

for statement: loops the code block a specified number of times;

foreach statement: iterates through each element in the array and loops the code block;

Some newcomers may ask under what circumstances should loop statements be used?

Of course when writing code, we often need to run the same block of code repeatedly. We can use loops to perform such tasks instead of adding several almost equal lines of code to the script.

Finally, I would like to recommend the latest and most comprehensive "PHP Video Tutorial"~ Come and learn!

The above is the detailed content of Example of how to terminate or interrupt a loop in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn