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 trialrob111
8,379 PointsWhy 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
Anton Williams
5,157 PointsThe 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
8,379 Pointsrob111
8,379 PointsThanks for the reply.
One more question.. is this a standard PHP way of writing code or is this unique to WP?
Anton Williams
5,157 PointsAnton Williams
5,157 PointsYes it's a standard way, it's just a shorthand version. you can also do:
can go shorthand to
$bar = ( isset($foo) ? true : false );
Alena Holligan
Treehouse TeacherAlena Holligan
Treehouse Teachergreat answer :) the if statement and while statements will both have corresponding end statements.
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.