Home  >  Article  >  Backend Development  >  PHP语法(3):控制结构(For循环/If/Switch/While)

PHP语法(3):控制结构(For循环/If/Switch/While)

WBOY
WBOYOriginal
2016-06-13 12:27:40784browse

PHP语法(三):控制结构(For循环/If/Switch/While)

相关链接:

PHP语法(一):基础和变量

PHP语法(二):数据类型、运算符和函数

PHP语法(三):控制结构(For循环/If/Switch/While)

本文我来总结几个PHP常用的控制结构,先来个最特别的foreach,剩下的控制结构跟其他语言差不多,那这一期就比较简单了。


Foreach循环

遍历数组中的每个元素并循环代码块。

用法:foreach ( $array as $value )

每进行一次循环迭代,当前数组元素的值就会被赋值给 $value 变量,并且数组指针会逐一地移动,直到到达最后一个数组元素。

<code>    $age=array("Bill"=>"35","Steve"=>"37","Peter"=>"43");    foreach($age as $x=>$x_value) {      echo "Key=" . $x . ", Value=" . $x_value;    }</code>

For循环

基本的for循环如下:

<code>    for ($x=0; $x</code>

If判断

if没有什么特别的用法。

<code>if (条件) {  条件为 true 时执行的代码;} elseif (condition) {  条件为 true 时执行的代码;} else {  条件为 false 时执行的代码;}</code>

Switch

switch也是跟C++差不多。

<code>switch ($x){case 1:  echo "Number 1";  break;case 2:  echo "Number 2";  break;default:  echo "No number between 1 and 3";}</code>

While

<code>while (条件为真) {  要执行的代码;}</code>

Do while

do...while 循环首先会执行一次代码块,然后检查条件,如果指定条件为真,则重复循环。

<code>do {  要执行的代码;} while (条件为真);</code>

最后

回顾开博这几天的历程,又看到园子里其他博主写的“为什么不分享”的文章,感概良多。其实愿意分享的人还是很多,但是不分享的原因有太多了,没时间、懒、怕被笑话都是因素。本来看看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