if – PHP Reference Book Blog https://phpreferencebook.com/ PHP Reference: Beginner to Intermediate PHP5 Sun, 01 Oct 2017 17:21:19 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.13 Control Structures Without Curly Braces https://phpreferencebook.com/clarifications/control-structures-curly-braces/ Fri, 02 Jan 2009 17:00:53 +0000 https://phpreferencebook.com/?p=44 Continue reading 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
}else{
// 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.

]]>