Home >Backend Development >PHP Problem >An in-depth analysis of three ways to break out of loops in PHP

An in-depth analysis of three ways to break out of loops in PHP

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-03-19 10:20:583592browse

This article will give you an in-depth understanding of the three methods of jumping out of the loop in PHP (contiue, break and exit). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

An in-depth analysis of three ways to break out of loops in PHP

Three ways to break out of the loop in php

1.break statement

1. Used for switch statements, for, while, do...while, foreach, used to interrupt statements.

2. The number followed by break indicates how many levels of loops to jump out of. By default, no number is added to indicate one level of loops to jump out of.

3. A loop can contain multiple break statements, but only the statement executed for the first time is valid.

<?php
for ($i=0; $i <5 ; $i++) { 
    for ($j=0; $j <5 ; $j++) { 
        echo $j;
        echo &#39;<br />&#39;;
        break;
    }
    echo $i;
}
?>

The running result is:

An in-depth analysis of three ways to break out of loops in PHP

But if we add 2 after break, the output result will be 0.

2. The continue statement

can only be used in loop statements. Breaking out of this loop does not end the entire loop.

<?php
for ($i=0; $i <5 ; $i++) { 
    for ($j=0; $j <5 ; $j++) { 
        echo $j;
        continue;
    }
    echo $i;
    echo &#39;<br />&#39;;
}
?>

The result of its operation is:

An in-depth analysis of three ways to break out of loops in PHP

##Three.exit() statement/die statement

Ends the execution of the entire program, which is a function.

Syntax:exit(parameter)

If the parameter is a string, the function will output the string before exiting. If the argument is an integer, this value will be used as the exit status. The exit status value is between 0 and 254. Exit status 255 is reserved by PHP and will not be used. Status 0 is used to terminate the program successfully.

<?php
for ($i=0; $i <5 ; $i++) { 
  for ($j=0; $j <5 ; $j++) { 
    echo $j;
    exit();
    }
  echo $i;
  echo &#39;<br />&#39;;
}
?>

It ends the entire program directly, so the result after we run it is only 0.

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of An in-depth analysis of three ways to break out of loops 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