tags:

views:

143

answers:

4

I saw the following 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.

+2  A: 

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

Steve
+7  A: 

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.

Felix Kling
+3  A: 

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> 
Caleb Thompson
A: 

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';
John Isaacks
The *shorthand if-else statement* is called [ **ternary operator** ](http://en.wikipedia.org/wiki/Ternary_operation).
Felix Kling
@Felix Thanks for the info!
John Isaacks