Everything PHP: Alternative Syntax for Control Structures

Published on Mar 17, 2009   //  Development

Everything PHP

PHP’s syntax occasionally has multiple ways to achieve the same result. Today we’ll be talking about an alternative syntax for some of the control structures. These alternative syntaxes are there because other programming languages use these syntaxes, and PHP wants to give developers the choice of which to use (as they may already be used to a different format).

Colon Syntax

One of the alternative syntaxes for the if, while, foreach, switch and for control structures is called the colon syntax. This is where you replace the { with a colon and the } with either endif;, endwhile;, endforeach;, endswitch; or endfor; (respectively). Note that when using the colon syntax with if/else/elseif statements, else and elseif have no “end” statement, and the endif; goes after all the else/elseifs. Let’s look at a couple of examples:

if

[code='php']if ($foo == $bar):
return true;
endif;[/code]

if/else/elseif

[code='php']if ($foo == bar):
return true;
elseif ($foo == "bar"):
return true;
else:
return false;
endif;[/code]

for

[code='php']for ($x=0; $x < count($foobar); $x++):
echo $x;
endfor;[/code]

Shortform

This is also a shortform syntax for if, while, for and foreach. This shortform can only be used when you're executing a one-line statement within it. The shortform syntax removes the curly brackets. You should indent the statement one tab for readability purposes (I just can't do that within these code blocks, sorry). Here's a couple of examples:

if

[code='php']if ($foo == $bar)
return true;[/code]

if/else/elseif

[code='php']if ($foo == $bar)
return true;
elseif ($foo == "bar")
return true;
else
return false;[/code]

foreach

[code='php']foreach ($array as $value)
echo $value;[/code]

Conclusion

PHP has multiple syntaxes for certain control structures. It is up to you to decide which syntax you prefer most, or (in the case of the shortform syntax) is easiest to use.

1 Comment to “Everything PHP: Alternative Syntax for Control Structures”

  • Versatility is what is needed to keep market share, and this is a prime example of that. Nobody really wants to learn new tricks, do they?