php 跳出foreach / for循环实现程序
现在在php跳出循环方法有几种,一种是使用goto另一种是使用php新特性goto命令哦,下面我来一下介绍介绍。
break是被用在上面所提的各种循环和switch语句中的。他的作用是跳出当前的语法结构,执行下面的语句。break语句可以带一个参数n,表示跳出循环的层数,如果要跳出多重循环的话,可以用n来表示跳出的层数,如果不带参数默认是跳出本重循环
//php当前循环为1,循环由里到外依次递增,break默认为1,例如跳出第2层循环
代码如下 | 复制代码 |
for ($i=0;$i
foreach (array(1,2,3) as $val){ foreach (array(1,2,3) as $val){ echo "1层循环 "; break 2; //跳出第2层循环 } echo "2层循环 "; } echo "3层循环 "; } |
//结果:
//1层循环
//3层循环
//1层循环
//3层循环
//1层循环
//3层循环
goto
goto实际上只是一个运算符,和其他语言一样,PHP中也不鼓励滥用goto,滥用goto会导致程序的可读性严重下降。goto的作用是将程序的执行从当前位置跳转到其他任意位置,goto本身并没有要结束的循环的作用,但其跳转位置的作用使得其可以作为跳出循环使用。但PHP5.3及以上版本停止了对goto的支持,所以应该尽量避免使用goto。
下面的是一个使用了goto跳出循环的例子
代码如下 | 复制代码 |
for($i = 1000;$i >= 1 ; $i– ){ if( sqrt($i) goto a; } echo “$i”; } a: echo” this is the end”; |
例子中使用了goto来跳出循环,这个例子用来检测1000以内,那些数的平方根大于29

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1
Powerful PHP integrated development environment
