时间: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)两种书写方式不能混合只能使用其中一种。