Control Structures Without Curly Braces

In the book I cover the standard syntax methods for if, elseif, else, while, do-while, switch, for, and foreach. Here is the if statement syntax:

if (expr) {
// If expr is TRUE,  do this, then exit the IF loop
}elseif (expr2) {
// If expr is FALSE, and expr2 is TRUE, do this, then exit the loop
// If all expr's are FALSE, do this, then exit

While accurate, there is a shorthand method that does not involve the curly bracket. If there is only a single evaluation, you can remove the curly braces completely. The following two examples are both completely valid syntax for control structures:

if ($a == 1) echo $a;
if ($a == 1) {echo $a; $a=2;}

Now, I still recommend using curly brackets, if only for clarity and consistency (excluding them for the second line above would make your life much harder than necessary, but I thought a clarification was in order. For more information on Control Structions, check out chapter 3, pages 25-32 of the free PHP book PDF.

Similar Posts: