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

Alex Flores
Alex Flores
7,864 Points

PHP Endwhile & Endif

Hey all,

I'm currently learning The WordPress Template Hierarchy and there's this code in index.php that goes:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
         <div class="page-header">
                    <h1><?php the_title(); ?> </h1>
         </div>

         <?php endhile; else: ?>
                <div class ="page-header">
                     <h1> Oh no </h1>
                </div>
          <?php endif; ?>

There are a few things that I don't get:

  1. What is endwhile and endif?

  2. What does ":" mean exactly?

  3. Why are they opening so many <?php ?> tags? Won't one suffice? I did the PHP basic course and they didn't cover any of this syntax.

Any help would be appreciated!

1 Answer

Here's an excerpt from the PHP documentation that might help:

Alternative syntax for control structures ΒΆ

(PHP 4, PHP 5, PHP 7)
PHP offers an alternative syntax for some of its control structures; 
namely, if, while, for, foreach, and switch. In each case, the basic 
form of the alternate syntax is to change the opening brace to 
a colon (:) and the closing brace to endif;, endwhile;, endfor;, 
endforeach;, or endswitch;, respectively.

<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>
In the above example, the HTML block "A is equal to 5" is nested 
within an if statement written in the alternative syntax. The HTML 
block would be displayed only if $a is equal to 5.

The alternative syntax applies to else and elseif as well. The following 
is an if structure with elseif and else in the alternative format:

<?php
if ($a == 5):
    echo "a equals 5";
    echo "...";
elseif ($a == 6):
    echo "a equals 6";
    echo "!!!";
else:
    echo "a is neither 5 nor 6";
endif;
?>
Note:
Mixing syntaxes in the same control block is not supported.

Here's a link to the source: http://php.net/manual/en/control-structures.alternative-syntax.php