What is the purpose of: (colon) in PHP?

10

I have this question that is leaving me with fleas behind the ear. I do not understand, not at all.

What does the sign for : have two points. Can anyone explain me?

Example:

if ( have_posts() ) : while ( have_posts() ) : the_post();

    
asked by anonymous 20.06.2017 / 22:01

2 answers

17

This is an alternate syntax for a block that is delimited by { } keys. In this case the opening becomes the two points : and the closing is a end followed by the name instruction that started can be a endif , endforeach etc. This syntax applies the if, while, for, foreach, and switch instructions.

$arr = range(1,5);

foreach ($arr as $item){
    echo $item .'<br>';
}

The same code with the other syntax.

$arr = range(1,5);

foreach ($arr as $item):
    echo $item .'<br>';
endforeach;

Documentation

    
20.06.2017 / 22:12
10

Complementing @rray's response. You'll also find the colon sign : as part of the ternary operator ?: used for conditions.

See an example:

$user = "gato";

echo ($user === "gato") ? "meow" : "nao eh um gato :(";

Output:

  

Meow

See more in the documentation .

    
20.06.2017 / 22:29