22
votes

Possible Duplicate: What is “:” in PHP?

What does the : mean in the following PHP code?

<?php
    while (have_posts()) : the_post();
?>
7
this is the alternate syntax of some language construct like if while foreachShakti Singh
Hard to find, but some explanations here: Reference - What does this symbol mean in PHP?mario

7 Answers

38
votes

It's called an Alternative Syntax For Control Structures. You should have an endwhile; somewhere after that. Basically, it allows you to omit braces {} from a while to make it look "prettier"...

As far as your edit, it's called the Ternary Operator (it's the third section). Basically it's an assignment shorthand.

$foo = $first ? $second : $third;

is the same as saying (Just shorter):

if ($first) {
    $foo = $second;
} else {
    $foo = $third;
}
12
votes

There is an example listed in the documentation for while that explains the syntax:

Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

while (expr):
    statement
    ...
endwhile;

An answer over here explains it like this:

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>
8
votes

it's like:

<?php
while(have_posts()) {
    the_post();
}
?>
5
votes

This notation is to avoid the use of curly braces - generally when embedding PHP within HTML - and is equivalent to:

while (have_posts())
{
    the_post();
}
3
votes

It's saying while have_posts() is true run the_post().

2
votes
while (expression is true : code is executed if expression is true)
-2
votes
while(expression = true) : run some code ;