Control flow constructs are a fundamental element that modern programming languages almost always contain. Control flow constructs regulate the order in which statements in a program are executed.Two types of control flow constructs are conditionals and loops.
Statements that are performed only if a certain condition is true are conditionals, and statements that are executed repeatedly are loops.
15 Code Formatting and Layout
The ability to test and act on conditionals allows you to implement logic to make decisions in code. Similarly, loops allow you to execute the same logic repeatedly, per-forming complex tasks on unspecified data.
Using Braces in Control Structures
PHP adopts much of its syntax from the C programming language. As in C, a single-line conditional statement in PHP does not require braces. For example, the following code executes correctly:
if(isset($name)) echo “Hello $name”;
However, although this is completely valid syntax, you should not use it.When you omit braces, it is difficult to modify the code without making mistakes. For example, if you wanted to add an extra line to this example, where $nameis set, and weren’t paying close attention, you might write it like this:
if(isset($name)) echo “Hello $name”;
$known_user = true;
This code would not at all do what you intended.$known_useris unconditionally set to
true, even though we only wanted to set it if $namewas also set.Therefore, to avoid confusion, you should always use braces, even when only a single statement is being con-ditionally executed:
if(isset($name)) { echo “Hello $name”; }
else {
echo “Hello Stranger”; }
Consistently Using Braces
You need to choose a consistent method for placing braces on the ends of conditionals.
There are three common methods for placing braces relative to conditionals:
n BSD style, in which the braces are placed on the line following the conditional, with the braces outdented to align with the keyword:
if ($condition) {
// statement }
n GNU style, in which the braces appear on the line following the conditional but are indented halfway between the outer and inner indents:
if ($condition) {
// statement }
n K&R style, in which the opening brace is placed on the same line as the key-word:
if ($condition) { // statement }
The K&R style is named for Kernighan and Ritchie, who wrote their uber-classic The C Programming Language by using this style.
Discussing brace styles is almost like discussing religion. As an idea of how contentious this issue can be, the K&R style is sometimes referred to as “the one true brace style.”
Which brace style you choose is ultimately unimportant; just making a choice and stick-ing with it is important. Given my druthers, I like the conciseness of the K&R style, except when conditionals are broken across multiple lines, at which time I find the BSD style to add clarity. I also personally prefer to use a BSD-style bracing convention for function and class declarations, as in the following example:
Function hello($name) {
echo “Hello $name\n”; }
The fact that function declarations are usually completely outdented (that is, up against the left margin) makes it easy to distinguish function declarations at a glance.When coming into a project with an established style guide, I conform my code to that, even if it’s different from the style I personally prefer. Unless a style is particularly bad, consisten-cy is more important than any particular element of the style.
forVersus while Versus foreach
You should not use a whileloop where a fororforeachloop will do. Consider this code:
function is_prime($number) {
$i = 2;
while($i < $number) {
if ( ($number % $i ) == 0) { return false;
}
$i++;
17 Code Formatting and Layout
}
return true;
}
This loop is not terribly robust. Consider what happens if you casually add a control flow branchpoint, as in this example:
function is_prime($number)
while($i < $number) {
// A cheap check to see if $i is even
In this example, you first check the number to see whether it is divisible by 2. If it is not divisible by 2, you no longer need to check whether it is divisible by any even number (because all even numbers share a common factor of 2).You have accidentally preempted the increment operation here and will loop indefinitely.
Usingforis more natural for iteration, as in this example:
function is_prime($number)
When you’re iterating through arrays, even better than using foris using the foreach operator, as in this example:
$array = (3, 5, 10, 11, 99, 173);
foreach($array as $number) { if(is_prime($number)) {
print “$number is prime.\n”; }
}
This is faster than a loop that contains a forstatement because it avoids the use of an explicit counter.
Using break and continue to Control Flow in Loops
When you are executing logic in a loop, you can use breakto jump out of blocks when you no longer need to be there. Consider the following block for processing a configu-ration file:
$has_ended = 0;
while(($line = fgets($fp)) !== false) { if($has_ended) {
} else {
if(strcmp($line, ‘_END_’) == 0) {
$has_ended = 1;
}
if(strncmp($line, ‘//’, 2) == 0) { }
else {
// parse statement }
} }
You want to ignore lines that start with C++-style comments (that is,//) and stop pars-ing altogether if you hit an _END_ declaration. If you avoid using flow control mecha-nisms within the loop, you are forced to build a small state machine.You can avoid this ugly nesting by using continueandbreak:
while(($line = fgets($fp)) !== false) { if(strcmp($line, ‘_END_’) == 0) {
break;
}
if(strncmp($line, ‘//’, 2) == 0) { continue;
}
19