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

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 that using ":" in php code.

+3
source share
4 answers

This is an alternative syntax for control structures .

So,

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

equivalently

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

This can come in handy when working with HTML. Imho, it’s easier to read because you don’t have to look for curly braces {}, and the PHP code and HTML don't mix. Example:

<?php if(somehting): ?>

    <span>Foo</span>

<?php else: ?>

    <span>Bar</span>

<?php endif; ?>

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

+8
source

: php html.

, . . : if, while, for, foreach ..

::

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

':'

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

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

+2
source

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

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

Which is equivalent:

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

Source: https://habr.com/ru/post/1755050/