What does ":" mean in PHP?

  • Added:
  • |
  • In: Basic PHP

Possible Duplicate: What is “:” in PHP?

What does the : mean in the following PHP code?

<?php 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:

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

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()) { the_post(); } 

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> 

I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

Connect Social With PHPAns