Alternate Colon Syntax

If you're like me, you must be still figuring out the best way to indent your PHP control structures like if(), for(), while(), foreach() and even switch()!

The 2 popular PHP control structure 'styles'

The 2 most common styles used in many PHP scripts I have seen are:

php:


<?php

/* STYLE I */
// What everybody seems to prefer
// ------------------------------
if( $a>=10000 )  {
  echo 'Too much!';
}
elseif( $a<=5000 ) {
  echo 'Too little!';
}
else {
  echo 'Just nice!';
}

/* STYLE II */
// What I personally USED to prefer
// --------------------------------
if( $a>=10000 )
{
  echo 'Too much!';
}
elseif( $a<=5000 )
{
  echo 'Too little!';
}
else
{
  echo 'Just nice!';
}

?>


The point here is that we usually use the curly braces to help 'control' our PHP control structures but this is no longer necessary... well, at least for me!

Style 3: Alternative syntax for control structures

One day recently, I was reading the PHP Manual and came across this interesting piece of information that I never knew about previously - it's about using the colon ( : ) and the appropriate keyword where you would normally place your opening and closing curly braces.

The following code will quickly show you what I mean:

php:


<?php

// IF() sample
// --------------------------------
if( $a>=10000 ): // note the colon
  echo 'Too much... ';
  echo 'you\'re too kind!';
elseif( $a<=5000 ): // here too
  echo 'Too little... ';
  echo 'I think you need it more than me!';
else: // yet again
  echo 'Just nice... ';
  echo 'I\'ll put you on my Christmas list!';
endif; // the keyword!

// FOR() sample
// --------------------------------
for( $i=1; $i<11; $i++ ):
  echo 'Number '.$i;
endfor;

?>


The appropriate keywords

Here are the keywords for the following control structures:

code:
 CS       | (ending) KEYWORD
----------|-----------------
 if()     | endif
 for()    | endfor
 while()  | endwhile
 foreach()| endforeach
 switch() | endswitch

TOP

Do you find it easy to navigate through this site?

 Yes

 No

 Where am I?