PHP offers an alternative way to write their control structures for as long as I’ve remembered. It basically does away with the curly brackets and replaces the opening curly with a colon (:) and the closing with ‘end’-whatever. I have to be honest and say I’ve never really found a need to use the alternative syntax, simply because I’m so used to using the curly braces after so many years of using PHP. Plus, it’s less typing!

But having spend time working on CodeIgniter projects, I have found myself adopting this alternative syntax when it comes to buidling the CI’s views templates. I appreciate that there is place in the PHP universe for this alternative coding style.

The best time to use this alternative style is when you need to mix PHP codes with HTML. In CI, this normally happens in views. Have a look at the IF example below of a typical HTML table layout:

Site Name Site URL Site Owner
- - -

The same table can be written in the alternative style as:

Site Name Site URL Site Owner
- - -

Personally, I find the alternative syntax gels better with HTML even though it’s more verbose. But because this form is more verbose, if a HTML developer was to look at this, I would imagine the second example would make more sense and easier to read and understand than the first table.

This alternative form works for PHP’s ‘if’, ‘switch’, ‘while’, ‘for’ and ‘foreach’ control statements.

See Everything PHP’s article on Alternative Syntax for Control Structures for more examples.

Alternative short form ‘if-else’ statement
There is also another shorter way of writing the ‘if-else’ statements which I also found very useful in my CI views. Take for example the following:

This can be written as:

The portion before the ‘?’ is the condition, followed by the ‘true’ outcome, then colon, then the ‘false’ outcome.

This helps to keep the coding of ‘if-else’ to the minimum, especially when you have to perform a lot of validation type check which could be a whole stack of ‘if-else’ statements.