if和else语句中":"的用法是什么?

q09*_*987 3 php

我看到了以下代码片段:

<?php
if(!empty($_POST)): // case I: what is the usage of the :
if(isset($_POST['num']) && $_POST['num'] != ''):

$num = (int)$_POST['num'];

....

if($rows == 0):
echo 'No';

else: // case II: what is usage of :
echo $rows.'Yes';

endif;
Run Code Online (Sandbox Code Playgroud)

我想知道php代码中":"的用法是什么.

Fel*_*ing 8

这是控制结构替代语法.

所以

if(condition):
    // code here...
else:
    // code here...
endif;
Run Code Online (Sandbox Code Playgroud)

相当于

if(condition) {
    // code here...
} else {
    // code here...
}
Run Code Online (Sandbox Code Playgroud)

在处理HTML时,这非常方便.Imho,它更容易阅读,因为你不必寻找大括号{},PHP代码和HTML不会混淆.例:

<?php if(somehting): ?>

    <span>Foo</span>

<?php else: ?>

    <span>Bar</span>

<?php endif; ?>
Run Code Online (Sandbox Code Playgroud)

我不会在"普通"PHP代码中使用替代语法,因为这里的大括号提供了更好的可读性.