Posted by : Chris London in (Programming, Tutorial)

Colon Syntax in PHP

Tagged Under : , ,

Colon syntax is another way to style your PHP code. Instead of using curly braces you use colons. Below I have included an example of a couple different curly brace styles and also each statement using the colon syntax. I don’t know of any performance benefits or loss to using this syntax over any other. Please comment here if you have any more information about its affects on performance.


Common Coding Styles

My personal favorite:

for (condition) {
     // code here
} elseif (condition) {
     // code here
}

A very common coding style:

for (condition)
{
     // code here
}
else if
{
     // code here
}

My Schpeel About Indenting

Indenting is the absolute most crucial element in coding style. I don’t personally care where people put their braces as long as the indentations are correct. When you have no indentation or incorrect indentation it’s an utter nightmare trying to debug any issues.

Colon Syntax in PHP

PHP has a syntax that is very common in WordPress code but isn’t used much outside of it. This syntax is colon syntax. Basically you use a colon for opening braces and then an endstatement; for the closing brace. Here are examples for each of the different statements that support colon syntax:

if statement:

if (condition) :
     // code here
elseif (condition) :
     // code here
else :
     // code here
endif;

switch statement:

switch (condition) :
     case (condition) :
          // code here
     break;
     case (condition) :
          // code here
     break;
     default :
          // code here
     break;
endswitch;

for loop:

for (expression; expression; expression) :
     // code here
endfor;

foreach loop:

foreach (expression) :
     // code here
endforeach;

while loop:

while (condition) :
     // code here
endwhile;

NOTE: do ... while loops are not support with the colon syntax!

I hope you have enjoyed this tutorial. Make sure and share this article with others if you liked it!

Share and Enjoy:
  • Facebook
  • Twitter
  • Add to favorites
  • email
  • Google Bookmarks

Comments:

Make a comment