>php教程 >php手册 >php continue与其他语言不同之处

php continue与其他语言不同之处

WBOY
WBOY원래의
2016-06-06 20:02:131332검색

switch,while等都是PHP非常常用的循环,而能够用好循环,对于使用PHP来编写有较强逻辑性的程序来说是非常不错的。 break是跳出循环,而continue是进行下一次循环。 很多东西手册上有,最重要的是如何把他们运用到实际当中去。 以下为摘抄的部分 continue 在

switch,while等都是PHP非常常用的循环,而能够用好循环,对于使用PHP来编写有较强逻辑性的程序来说是非常不错的。 break是跳出循环,而continue是进行下一次循环。 很多东西手册上有,最重要的是如何把他们运用到实际当中去。

以下为摘抄的部分

continue 在循环结构用用来跳过本次循环中剩余的代码并在条件求值为真时开始执行下一次循环。 continue 接受一个可选的数字参数来决定跳过几重循环到循环结尾。

<span><?php </span> 
<span>while</span> <span>(</span><span>list</span> <span>(</span><span>$key</span><span>,</span> <span>$value</span><span>)</span> <span>=</span> <span>each</span><span>(</span><span>$arr</span><span>)</span><span>)</span> <span>{</span> 
<span>if</span> <span>(</span><span>!</span><span>(</span><span>$key</span> <span>%</span> <span>2</span><span>)</span><span>)</span> <span>{</span> <span>// skip odd members </span>
<span>continue</span><span>;</span> 
<span>}</span> 
do_something_odd<span>(</span><span>$value</span><span>)</span><span>;</span> 
<span>}</span> 
 
<span>$i</span> <span>=</span> <span>0</span><span>;</span> 
<span>while</span> <span>(</span><span>$i</span><span>++</span> <span> <span>5</span><span>)</span> <span>{</span> 
<span>echo</span> <span>"Outer<br><span>\n</span>"</span><span>;</span> 
<span>while</span> <span>(</span><span>1</span><span>)</span> <span>{</span> 
<span>echo</span> <span>"  Middle<br><span>\n</span>"</span><span>;</span> 
<span>while</span> <span>(</span><span>1</span><span>)</span> <span>{</span> 
<span>echo</span> <span>"  Inner<br><span>\n</span>"</span><span>;</span> 
<span>continue</span> <span>3</span><span>;</span> 
<span>}</span> 
<span>echo</span> <span>"This never gets output.<br><span>\n</span>"</span><span>;</span> 
<span>}</span> 
<span>echo</span> <span>"Neither does this.<br><span>\n</span>"</span><span>;</span> 
<span>}</span> 
<span>?></span></span></span>

省略 continue 后面的分号会导致混淆。以下例子示意了不应该这样做。

<span><?php </span> 
<span>for</span> <span>(</span><span>$i</span> <span>=</span> <span>0</span><span>;</span> <span>$i</span> <span> <span>5</span><span>;</span> <span>++</span><span>$i</span><span>)</span> <span>{</span> 
<span>if</span> <span>(</span><span>$i</span> <span>==</span> <span>2</span><span>)</span> 
<span>continue</span> 
<span>print</span> <span>"<span>$i</span><span>\n</span>"</span><span>;</span> 
<span>}</span> 
<span>?></span></span></span>


希望得到的结果是:

0 1 3 4

可实际的输出是: 2


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.