Chapter 4
From Phpmaniac
Contents |
Control Structures
Control structures are what allows you to make your scripts truly dynamic. They allow you to change the output based on the input.
if
If is one of the first control structures that people learn, it allows you to do actions based on a condition.
- if(date(“a”) == “am”)
- {
- print(“It is morning!”);
- }
else
The else control structure is placed after an if block, it allows you to specify what to do if a condition or set of conditions are not met, a default action if you will.
- if(date(“a”) == “am”)
- {
- print(“It is morning!”);
- }
- else
- {
- print(“It is not Morning!”);
- }
else if
The else if control structure is placed after an if/else if block to specify another set of criteria if the above criteria are not met.
- if(date(“a”) == “am”)
- {
- print(“It is morning!”);
- }
- else if(date(“l”) == “Saturday”)
- {
- print(“It's Saturday!”);
- }
- else
- {
- print(“It is not morning or a Saturday!”);
- }
for
The for control structure allows you to iterate or loop through a piece of code a specific number of times.
- for($ix =0; $ix < 100; $ix++)
- {
- print(“Iteration: ” . $ix);
- }
while
The while control structure another tool for looping. Unlike the for loop, while will only iterate through the code if a condition is met, and will continue to iterate through the code until the condition is no longer met.
- $string = “”;
- while(strlen($string) < 20)
- {
- $string .= $string . “1”;
- }
do while
The do while control structure is similar to while except that it will iterate through the code block at least once.
- $ix = 0;
- do
- {
- print(“looping: ” . $ix++);
- } while ($ix < 50);

