Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

rob111
rob111
8,379 Points

Why does some PHP end in : instead of ;

While watching many of the Wordpress videos on here I noticed the php code ending in

:

instead of

;

Can someone point me in the right direction? I'm not familiar with why php would end this way

Here is an example

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

or

<?php endwhile; else : ?>

1 Answer

The statements that end in ; are the end of a command or function. like:

echo "this ends in a semicolon";

After the semicolon, it will move onto the next statement.

Statements like:

if ( x == true ) :

The colon is used here after the if statement instead of the usual curly brackets. Here is what the full thing looks like:

if ( x == true ):
//do code
else:
//do other code
endif;

Instead of:

if ( x == true ) {
//do code
}else{
//do other code
}

Your example broken down:

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

Goes to:

if ( have_posts() ) {
  while ( have_posts() ){
    the_post();
  }
}
rob111
rob111
8,379 Points

Thanks for the reply.

One more question.. is this a standard PHP way of writing code or is this unique to WP?

Yes it's a standard way, it's just a shorthand version. you can also do:

if (isset($foo)
{
$bar = true;
}
else
{
$bar = false;
}

can go shorthand to

$bar = ( isset($foo) ? true : false );
Alena Holligan
Alena Holligan
Treehouse Teacher

great answer :) the if statement and while statements will both have corresponding end statements.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
//more code in the while loop
<?php endwhile; ?>
//possibly more code in the if statement
<?php endif; ?>

This way of writing command statements is often used when the php is closed between each piece and there is HTML written. Most people find it easier to read and keep track of then a bunch of lone curly braces.