流程控制的替代语法

PHP 提供了一些流程控制的替代语法,包括 if while for foreach switch 。替代语法的基本形式是把左花括号({)换成冒号(:),把右花括号(})分别换成 endif; endwhile; endfor; endforeach; 以及 endswitch;

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

在上面的例子中,HTML 内容“A is equal to 5”用替代语法嵌套在 if 语句中。该 HTML 的内容仅在 $a 等与 5 时显示。

替代语法同样可以用在 else elseif 中。下面是一个包括 elseif else if 结构用替代语法格式写的例子:

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

更多例子参见 while for if