Home > Tutorials > PHP > Control Structures
Control Structures
Control structures are the logical code blocks which are used to perform checks and loops. If you need to break out of a loop before it ends, use the break command. To break out of the current iteration of the loop (but continue the loop itself), use the continue command.
IF/THEN/ELSE statements
If statements take the form
if (<logical evaluation>) {
<code block>
}
elseif (<logical evaluation>) {
<code block>)
}
else {
<code block>)
}
Any number of elseif's may be used in an if/then/else block.
SWITCH/CASE statements
Switch/case blocks are used for checking a given variable for various values. They take the following form:
switch ($var) {
case <value 1>:
<code block>
break;
case <value 2>:
<code block>
break;
default:
<code block>
}
Note the use of the break command - if you do not break from a given case, code will continue to execute through the next case. There may be times when you want this to happen, though:
switch ($var) {
case 0:
echo "var is not positive.<br/>"
case 1:
case 2:
echo "var is less than 3 but not negative";
break;
case 3:
echo "var is 3";
}
By using this, you have 3 possible outputs for 4 separate cases, one of which has two lines of output.
DO/WHILE statements
do...while blocks and while blocks are virtually the same, the only difference is that do...while blocks will always be run at least once before a "while" check is made, and while blocks will check for an exit condition before the code block is run.
do...while block:
do{
<code block>
} while (<logical evaluation>);
while block:
while (<logical evaluation>) {
<code block>
};
FOR/FOREACH statements
for statements are just like any other language - iterate a variable through a given range, stepping by a given amount:
for ($var=0; $var<10; $var++) {
<code block>
}
foreach statements are used to iterate through arrays - perfect for associative arrays where you would otherwise not be able to loop through each index:
foreach ($var in $arr) {
<code block>
}
In the above example, $arr is an already existing array, and $var is set to a different index in $arr with each iteration.
Comment on this page:
Comments
No one has commented on this lesson yet. You can be the first!