What is the purpose of : (two points) in PHP?

Asked

Viewed 1,673 times

11

I have this question that is leaving me with a flea behind my ear. I don’t understand at all.

What does the sign of : two points. Someone can explain me?

Example:

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

  • I see you found these code snippets in wordpress, that’s not it?

  • Exactly! I am studying Wordpress from A to Z. I am believing that so I will become independent in PHP.

2 answers

19


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

$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

  • Thank you very much. I only knew the keys. Now it’s making sense.

  • I was in doubt about the two points within the "IF", it is also a condition, within a condition?

  • @Narsejo has an example to show?

10

Complementing the @rray response. You will also find the two-point sign : as part of the ternary operator ?: used for conditions.

Take an example:

$user = "gato";

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

Exit:

Meow

See more in the documentation.

  • This one I knew. It was exactly what was confusing me a lot. Now everything is making sense to me.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.