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

醉折花枝作酒筹
Release: 2023-03-08 20:46:01
Original
3557 people have browsed it

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;
}
?>
Copy after login

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;;
}
?>
Copy after login

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;;
}
?>
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template