search
HomeBackend DevelopmentPHP TutorialPHP中跳出多重循环使用break,continue,goto,return,exit的用法和区别

PHP中的循环结构大致有for循环,while循环,do{} while 循环以及foreach循环几种,不管哪种循环中,在PHP中跳出循环大致有这么几种方式,break,continue,return,exit,die,goto等。

下面将一一介绍他们的用法以及各自之间的区别。

(1)break

break是被用在上面所提的各种循环和switch语句中的。他的作用是跳出当前的语法结构,执行下面的语句。break语句可以带一个参数n,表示跳出循环的层数,如果要跳出多重循环的话,可以用n来表示跳出的层数,如果不带参数默认是跳出本重循环。

看下面这个多重循环嵌套的例子:

<p>for($i=1;$i<=10;$i++){</p>	for($j=1;$j<=10;$j++){<br />		$m=$i * $i + $j * $j;<br />		echo $m,"<br/>";<br />		if($m<90||$m>190) {<br />			break 2;<br />		}<br />	}<br /><p>}</p>

这里使用了break 2跳出了两重循环,你可以试验一眼,将2去掉,得到的结果是完全不一样的。如果不使用参数,跳出的只是本次循环,第一层循环会继续执行下去。

(2)continue

continue是用来用在循环结构中,控制程序放弃本次循环continue语句之后的代码并转而进行下一次循环。

continue本身并不跳出循环结构,只是放弃这一次循环。如果在非循环结构中(例如if语句中,switch语句中)使用continue,程序将会出错。

例如在下面的这段PHP代码片段中:

<p>for($i=1;$i<=100;$i++){</p>	if($i%3==0||$i%7==0){<br />		continue;<br />	}else{<br />		echo $i,"<br/>";<br />	}<br /><p>}</p>

(3)return

return语句是用来结束一段代码,并返回一个参数的。可以从一个函数里调用,也可以从一个include()或者require()语句包含的文件里来调用,也可以是在主程序里调用,如果是在函数里调用程序将会马上结束运行并返回参数,如果是include()或者require()语句包含的文件中被调用,程序执行将会马上返回到调用该文件的程序,而返回值将作为include()或者require()的返回值。

而如果是在主程序中调用,那么主程序将会马上停止执行。

下面是一个使用return退出循环的案例:

<p>for($i=1000;$i>=1;$i–){</p>	if(sqrt($i)>=29){<br />		echo $i,"<br/>";<br />	}else{<br />		return;<br />	}<br />}<br /><p>echo "本行将不会被输出";</p>

这里的例子和使用exit的效果是一样的。在循环结束条件,自然跳出,这个当然是最好理解了,当循环满足循环临界条件时就是自己退出。

(4)exit

exit是用来结束程序执行的。可以用在任何地方,本身没有跳出循环的含义。exit可以带一个参数,如果参数是字符串,PHP将会直接把字符串输出,如果参数是integer整形(范围是0-254),那个参数将会被作为结束状态使用。

下面是一个使用exit退出循环的案例:

<p>for($i=1000;$i>=1;$i–){</p>	if(sqrt($i)>=29){<br />		echo $i,"<br/>";<br />	}else{<br />		exit;<br />	}<br />}<br /><p>echo "本行将不会被输出";</p>

上面这个例子中直接在从循环里结束了代码的运行,这样会导致后面的代码都不会被执行,如果是在一个php web 页面里面,甚至连exit后面的html代码都不会被输出。

(5)die

die函数退出循环和exit退出是一样的,这里就不详细说明了。

(6)goto

goto实际上只是一个运算符,和其他语言一样,PHP中也不鼓励滥用goto,滥用goto会导致程序的可读性严重下降。goto的作用是将程序的执行从当前位置跳转到其他任意位置,goto本身并没有要结束的循环的作用,但其跳转位置的作用使得其可以作为跳出循环使用。

但PHP5.3及以上版本停止了对goto的支持,所以应该尽量避免使用goto。

下面的是一个使用了goto跳出循环的例子:

<p>for($i=1000;$i>=1;$i–){</p>	if(sqrt($i)<=29){<br />		goto a;<br />	}<br />	echo $i;<br />}<br />a:<br /><p>echo " this is the end";</p>

例子中使用了goto来跳出循环,这个例子用来检测1000以内,那些数的平方根大于29。

以上就是PHP中跳出循环的几种方式的简单总结。


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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor