Alternative Syntax

Alternative Syntax for Control Structures

Posted on: August 26th, 2013 by taff No Comments

 

PHP offers an alternative syntax, also known as colon syntax, for a number of control structures, including if, for, foreach and switch.

Here is an example of a nested foreach, if, else and switch using standard syntax.

Control Structures - Standard Syntax

$allowedExtensions = ["jpg", "gif", "png", "pdf"];
$filenames = ["test.jpg", "foo.gif", "temp.pdf", "spreadsheet.xls"];
foreach ($filenames as $filename){
$file_extn = substr($filename, strrpos($filename, '.')+1);
if ( true === in_array($file_extn, $allowedExtensions)){
switch( $file_extn ){
case "jpg":
case "gif":
case "png":
echo "Ohh ein Bildchen!";
break;
case "pdf":
echo "Ein PDF";
break;
}
echo "Output nach Switch";
}else{
echo "Dateityp verboten";
}
echo "Output nach if";
}

Using tabstops we can make this readable but what happens when the number of switch cases we need to check become so many that we need to scroll back up to see what structure opened the curly bracket we are currently looking at.

In my opinion using the alternative syntax makes it easier when browsing code to see where, what is closing.

Control Structures - Alternative Syntax

$allowedExtensions = ["jpg", "gif", "png", "pdf"];
$filenames = ["test.jpg", "foo.gif", "temp.pdf", "spreadsheet.xls"];
foreach ($filenames as $filename):
$file_extn = substr($filename, strrpos($filename, '.')+1);
if ( true === in_array($file_extn, $allowedExtensions)):
switch( $file_extn ): case "jpg":
case "gif":
case "png":
echo "Ohh ein Bildchen!";
break;
case "pdf":
echo "Ein PDF";
break;
endswitch;
echo "Output nach Switch";
else:
echo "Dateityp verboten";
endif;
echo "Output nach if";
endforeach;

It is important to point out that switch statements written in this format require the first case to be included with the statement. If you put the first case in a separate PHP block, you will get the following error:
Parse error: syntax error, unexpected T_INLINE_HTML, expecting T_ENDSWITCH or T_CASE or T_DEFAULT
I'm not sure exactly why PHP behaves this way, but it is a commonly made mistake that is not often explained or warned against.

You may want to find out more about the alternative Syntax