Page 57 - Open Soource Technologies 304.indd
P. 57
Deepak Mehta, Lovely Professional University Unit 3: Flow-Control Statements and PHP in Web Page
Introduction Notes
Flow control and iteration are two very useful features of most programming languages. Without
them all programs would have to be linear and if you wanted something to happen three times,
you would have to code it three times.
Flow control means exactly what it sounds like it should, controlling the flow of something. When
using flow control for programming, what you are doing is regulating the order in which the
code is executed, how many times it is executed, and if it is executed at all.
Programmatic flow control can be broken into three primary categories:
Conditionals
Conditionals allow us to specify whether or not to run a selected piece of code based on some
prior condition.
Iteration
Iteration, also known as looping, is to specify that a piece of code can be run multiple times.
Depending on circumstances, that can be one or more or zero or more times.
Goto’s
There is one last type of flow control, called goto’s, after the command that defined the process.
Even if languages still support this coding mechanism, none of them will admit to it. It makes
for bad code. Instead, our last topic in this brief look at good coding practices as they pertain to
working with effective flow control, functions and modularization.
3.1 Conditional Statements
Some statements in PHP are known as conditional statements. These statements make use of
statements that delimit them and which determine whether or not the delimited code is executed,
based on some condition.
We will look at two structures here:
• if statement
• switch statement
We will also look at some alternative methods for coding both statements (PHP likes to be flexible).
3.1.1 If Statement
In most C-style languages, there are two basic conditional statements—if statement and the switch
statement. PHP is no exception.
We are going to start with if statement. It is the easier of the two.
The if statement is a simple concept. If something is true, then perform the statement block
associated with it, otherwise do not. To use conditionals, you need to be evaluating expressions
that evaluates to true or false. We have discussed conditional operators elsewhere, but we can also
test for non-zero, non-null, non-empty values in variables, and many system defined functions
return true or false depending on their successful execution.
The if statement takes the form of the following:
if (conditional expression) {
statement block;
}
LOVELY PROFESSIONAL UNIVERSITY 51