开发者

What is the usage of ":" in if and else statements?

I saw the followin开发者_运维技巧g code snippet:

<?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;

I would like to know what the usage of ":" in php code is.


This is the alternative syntax for control structures.

So

if(condition):
    // code here...
else:
    // code here...
endif;

is equivalent to

if(condition) {
    // code here...
} else {
    // code here...
}

This can come very handy when dealing with HTML. Imho, it is easier to read, because you don't have to look for braces {} and the PHP code and HTML don't feel like mixed up. Example:

<?php if(somehting): ?>

    <span>Foo</span>

<?php else: ?>

    <span>Bar</span>

<?php endif; ?>

I would not use the alternative syntax in "normal" PHP code though, because here the braces provide better readability.


This : operator mostly used in embedded coding of php and html.

Using this operator you can avoid use of curly brace. This operator reduce complexity in embedded coding. You can use this : operator with if, while, for, foreach and more...

Without ':' operator

<body>   
<?php if(true){ ?>  
<span>This is just test</span>  
<?php } ?>  
</body>

With ':' operator

<body>  
<?php if(true): ?>  
<span>This is just test</span>  
<?php endif; ?>  
</body> 


Its the alternative syntax for control structures http://nz2.php.net/manual/en/control-structures.alternative-syntax.php


The only time I use a colon is in the shorthand if-else statement

$var = $bool ? 'yes' : 'no';

Which is equivalent to:

if($bool)
$var = 'yes';
else
$var = 'no';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜