Chapter 4

From Phpmaniac

Jump to: navigation, search

Return to Contents

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.

  1. if(date(“a”) == “am”)
  2. {
  3.   print(“It is morning!);
  4. }

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.

  1. if(date(“a”) == “am”)
  2. {
  3.   print(“It is morning!);
  4. }
  5. else
  6. {
  7.   print(“It is not Morning!);
  8. }

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.

  1. if(date(“a”) == “am”)
  2. {
  3.   print(“It is morning!);
  4. }
  5. else if(date(“l”) == “Saturday”)
  6. {
  7.   print(“It's Saturday!”);
  8. }
  9. else
  10. {
  11.  print(“It is not morning or a Saturday!”);
  12. }

for

The for control structure allows you to iterate or loop through a piece of code a specific number of times.

  1. for($ix =0; $ix < 100; $ix++)
  2. {
  3.   print(“Iteration:. $ix);
  4. }

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.

  1. $string = “”;
  2. while(strlen($string) < 20)
  3. {
  4.   $string .= $string .1;
  5. }

do while

The do while control structure is similar to while except that it will iterate through the code block at least once.

  1. $ix = 0;
  2. do
  3. {
  4.   print(“looping:. $ix++);
  5. } while ($ix < 50);

Return to Contents

Personal tools