Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Language Reference : Control Structures : Alternative syntax for control structures

Alternative syntax for control structures

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:

if ($a == 5):
"a equals 5";
elseif (
$a == 6):
"a equals 6";
"a is neither 5 nor 6";

See also while, for, and if for further examples.

Code Examples / Notes » control_structures.alternative_syntax


There is an other alternative syntax:
if ($a > 5) {
   echo "big";
} else {
   echo "small";
can be replaced by:
echo $a > 5 ? "big" : "small";


The bug in your example is user error.
$foobar = 2;
echo 'Foobar is ' . ($foobar == 2) ? 'foo' : 'bar';
// outputs 'foo';
echo 'Foobar is ' . (($foobar == 2) ? 'foo' : 'bar');
// outputs 'Foobar is foo';
When using the ? : operators you should always wrap the entire thing in parentheses to avoid the problem you describe. By my understanding, the issue an extension of your example:
$pet-type = 1;
$pet-name = 'Mittens';
echo 'My ' . ($pet-type == 1) ? 'cat' : 'puppy' . 'dog' . '\'s name is ' . $pet-name . '.';
// returns 'cat'
echo 'My ' . (($pet-type == 1) ? 'cat' : 'puppy' . 'dog') . '\'s name is ' . $pet-name . '.';
// returns 'My cat\'s name is Mittens.'
You see that without parentheses the parser has no way of differentiating between the false case and the rest of the string.

php dot net

Response to virtuall: This works as well, and I find it easier to read:
<?php if ($whatever): ?>
       $whatever is true
<?php else: ?>
       $whatever is false
<?php endif ?>


In response to virtuall:
The end_; structure sometimes makes it easier to tell which block statement end you are looking at.  It's much harder to tell which nested block a } belongs to than an end_;

php dot net

In response to spa:
Yeah, that's for sure! Seems so obvious, but remains a tough sell... I avoid the "Bracket Racket", and use it only where the (ahem) "Clearer Syntax" wasn't implemented.
A further improvement would be a "Noun-Verb" form of end structures. Such as:
if (...):
 while (...):
   if (...):
This would make it yet another level of easier to tell which block end you're looking at. ;-)


If you need nested ifs on I var its important to group the if so it works.
//Dont Works
//Parse error: parse error, unexpected ':'
$var='<option value="1" '.$status == "1" ? 'selected="selected"' :''.'>Value 1</option>';
$var='<option value="1" '.($status == "1" ? 'selected="selected"' :'').'>Value 1</option>';
echo $var;


If you need a tidy way to do a lot of condition testing, switch statement will do the job well:
switch (true){
   case ($a>0):
                    //do sth;
   case ($b>0):
                    //do sth;
   case ($c>0):
                    //do sth;
   case ($d>0):
                    //do sth;


If it needs saying, this alternative syntax is excellent for improving legibility (for both PHP and HTML!) in situations where you have a mix of them.
Interface templates are very often in need of this, especially since the PHP code in them is usually written by one person (who is more of a programmer) and the HTML gets modified by another person (who is more of a web designer). Clear separation in such cases is extremely useful.
See the default templates that come with WordPress 1.5+ ( for practical and smart examples of this alternative syntax.


I'd say this is nicer than that "endif" thing (not really an "alternative syntax", but):
<? if ($whatever) { ?>
 Whatever is true.
<? } else { ?>
 Whatever is false.
<? } ?>

i a m 4 w e b w o r k

Good tutorial on using alternative control structure syntax at:


as skippy noted above this is very useful stuff for interspersed php & html. Here is alternative syntax example using a bitwise comparison to set checkboxes on and off to prefill a permissions bitmask calculator form:
$bitmask = 481683;
.... [yada yada yada]....
<input type="checkbox" name="SOME_PERMISSION_VARIABLE" value="32768" <? echo($bitmask & 32768 ? "checked" : ""); ?>>Can perform some operation<br/>
<input type="checkbox" name="SOME_OTHER_PERMISSION_VARIABLE" value="65536" <? echo($bitmask & 65536 ? "checked" : ""); ?>>Can perform some other operation<br/>
You supply a bitmask, and it prechecks all the permissions the user has so you don't need to remember what they already have to recheck them all individually.
It's much more elegant than traditional if's.


As a rection on sttoo, if you use nested if's a bit different they are less likely to cause mistakes:
[EDITOR'S NOTE: Referenced Note has been removed]
$one = true;
$two = true;
$result = ($one ? "one" : ($two ? "two" : "none"));    // $result is "one"
$one = false;
$result = ($one ? "one" : ($two ? "two" : "none"));    // $result is "two"
$two = false;
$result = ($one ? "one" : ($two ? "two" : "none"));    // $result is "none"


As "qbolec" states, all the notes below which use the "?" are actually references to the ternary operator (").
Whilst this is kind of relevent, it probably shouldn't be in this section.

php dot net

Amen to what "atw" said.
It's really amazing how off-topic many notes on this page are. It is specifically about ENDcontrol structures. Of the twelve notes below, only one even mentions the word END. Perhaps only three or four are directly on-topic!


3 Lines to make table row colors alternate.  Could be used for other applications as well.
//1. Initialize alternating variable.
 //2. If alt var true set one color if false set the other.
 echo (($alt_color) ? "<tr bgcolor=\"#ffffff\">\n" : "<tr bgcolor=\"#D9E5F1\">\n");
 echo "<td>echo $row['id'];;</td>\n";
 echo "</tr>\n";
 //3. Alternate the variable value;
 (($alt_color) ? $alt_color=false : $alt_color=true);


(($alt_color) ? $alt_color=false : $alt_color=true);
would be way prettier as
$alt_color = not($alt_color);

sid trivedi

Expression - 1 (True or False) ? Expression - 2 (True) : Expression -3 (False);
Condition to be evaluated or Boolean Expression to be evaluated True or False ? Codes to be excuted , if true : codes to be executed, if false
The following codes can be replaced by following tenary expression as shown:
/*  // Codes replacement by tenary expression.
if($a == 1)
   $var = "Value is One";
else if($a == 24)
   $var = "24th Avenue";
   $var = "Not equal to One nor 24";
$var = $a == 1 ? "Value is One" : ($a == 24 ? "24th Avenue" : "Not equal to One nor 24");
echo "$var\n
Which generates following output as $a = 24
24th Avenue
More information on tenary expression can be found on following links:


<? while($row = $mysql_fetch_array($result)):?>
<tr bgcolor="<?=($i++ % 2)>0 ? '#FFFFFF' : '#FF0000' ?>">
<? endwhile;?>

Change Language

Follow Navioo On Twitter
Alternative syntax for control structures
eXTReMe Tracker