学习笔记 PHP中的流程控制书写方式有两种可选形式 [第二课]

时间:2014年2月13日

地点:刘家窑


1、下面是摘自PHP手册中的说明:

Alternative syntax for control structures

(PHP 4, PHP 5)

PHP offers an alternative syntax for some of its control structures;namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace toendif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.

<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?> 

In the above example, the HTML block "A is equal to 5" is nested within an if statement written in the alternative syntax. The HTML block would be displayed only if$a is equal to 5.

The alternative syntax applies to else and elseif as well. The following is anif structure with elseif and else in the alternative format:

<?php
if ($a == 5):
    echo 
"a equals 5";
    echo 
"...";
elseif (
$a == 6):
    echo 
"a equals 6";
    echo 
"!!!";
else:
    echo 
"a is neither 5 nor 6";
endif;
?> 

Note:

Mixing syntaxes in the same control block is not supported.

2、下面是在linux上的实验记录:


[kevinlou@centos php]$ vim structure.php

<?php
$a = 100;
if ($a>90):
    echo '$a > 90';
    echo "\n";
elseif ($a > 80):
    echo '$a > 80';
    echo "\n";
endif;

while ($a>10):
    echo $a;
    echo "\n";
    $a -= 10;
endwhile;

echo "\n\n";

for ($i=0;$i<$a;$i++):
    echo $a;
    echo "\n";
    $a--;
endfor;

echo "\n\n";

$arr = array(1,2,3,4,5,6,7,8,9,0);
foreach ($arr as $key=>$val):
    echo $key.'=>'.$val;
    echo "\n";
endforeach;


3、下面是运行结果:

[kevinlou@centos php]$ php structure.php
$a > 90
100
90
80
70
60
50
40
30
20


10
9
8
7
6


0=>1
1=>2
2=>3
3=>4
4=>5
5=>6
6=>7
7=>8
8=>9
9=>0


4、总结和说明:

 1)能够使用 冒号(:)和endxxx 语法的流程控制 只有列出的这几个  : if  while for foreach switch

 2)冒号必须紧跟在关键字后面的括号后面,不能有空格

 3)elseif 在这种书写方式下,只能连接在一起写,不能分开

 4)两种书写方式不能混合只能使用其中一种。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值