What does ":" mean in PHP?

  • Added:
  • |
  • In: Basic PHP

Possible Duplicate:What is “:” in PHP?

What does the : mean in the following PHP code?

    while (have_posts()) : the_post();
This Question Has 7 Answeres | Orginal Question | Paulo Coghi
while (expression is true : code is executed if expression is true)

it's like:

while(have_posts()) {

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;

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

while(expression = true) : run some code ;

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

while (have_posts())

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):

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

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

With (:) operator

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

Meet with owner

Sajjad Hossain

Hey, I am Sajjad, working in web development sector since 2012. I love to do amazing things. Let's do a project together.
Connect Social With PHPAns