Page 71 - Open Soource Technologies 304.indd
P. 71
Unit 3: Flow-Control Statements and PHP in Web Page
Notes
Example:
for ($x = 0; $x < 10; $x++;) {
$a = $a + $b[$x];
$x++;
}
For those who want to do things the hard way, you can also specify multiple conditions by putting
them in a comma separated list within the semicolon separated list.
for ($x=0,$y=0; $x<10,$y<20; $x++,incrF($y);) {
$a = $a + $b[$x];
$x++;
}
This iterative structure also has an alternative syntax.
for (init; condition; increment):
statements;
endfor;
for and while are not one-hundred percent interchangeable, so think about which one you want
to use before coding.
The for statement assumes some sort of incrementation, such as counting through a set of
something. It is designed for stepping through things.
Although any basic discussion of iteration tends to use incremental examples for both while and
for statements, the while statement is better suited for testing some flag or condition. A flag, in
programming terms, is a variable, usually Boolean, that refers to the current state of something
in the program. Our example above of using a while statement to walk an array is an example
where we are testing the contents of the elements of an array, not our position in it.
Develop a PHP program to differentiate between while and for statement.
3.4 Termination Statements
Sometimes you want to break out of a control statement early, perhaps because of an error or some
other condition that the conditional expression itself is not testing for. We have seen an example
of this already with the break statement used in a switch statement coding block.
Here we will look at various ways to prematurely terminate loops and conditionals by setting
multiple exit points.
3.4.1 The Break Statement
This statement breaks you out of the conditional statement and moves on to the first statement
outside of the conditional statement. When using break to get out of a condition, be aware that it
ignores if statements. This is so you can use an if statement to test whether you need to terminate
the current conditional.
LOVELY PROFESSIONAL UNIVERSITY 65