OUR MUST POPULAR POST

Thursday, April 11, 2013

PHP Tutorial: Logic Flow.

Controlling the flow of logic is a fundamental part of any program, including a PHP script, but what does the phrase actually mean?  Logic flow refers to the decision making process whereby you choose which actions to take under which circumstances.  Now let's say that is ordinary English!
Think for the moment of the process of filling a bath tub with water.  Here's a (greatly) simplified version of the decision making process involved:
  • Put some water in
  • Check the depth
    • Deep enough then quit
    • Not deep enough continue
  • Check the temperature
    • Too hot, then add some cold water and go back to "Check the depth"
    • Too cold, then add some hot water and go back to "Check the depth"
  • Add more water
  • Go back to "Check the depth"
This process illustrate the basic elements, or building blocks, of logic flow.  It has a start point, with an initialization routine (Put some water in.)  It continues with a cyclical routine, or loop, that is processed again and again until a certain condition is met.  This loop begins with "Check the depth", which is both the marker for the beginning of the loop, and the test for whether or not the whole process should be concluded.  The loop contains another condition test (Check the temperature) and three different process branches that are processed based on whether the temperature was too  hot, too cold or just right.  Each of these process branches returns to the beginning of the loop and the conclusion of the branch.
These fundamental building blocks are common to most programming languages, and vary mostly by the form of how they are implemented.  Here's how they are used in PHP:
The If Statement
The basic decision making statement, the "if" statement says "if this is true, do this, else do that".  Its format is like this:
if ( condition )
{ do these instructions }
else
{ do these instructions }
and here's an example:
if ($age < 21)
{ print "Minor"; }
else
{ print "Adult"; }
It is also possible to add a condition to the "else" side by using "elseif" like this:
if ($temp > $idealtemp)
{ print "Add cold water" }
elseif ($temp < $idealtemp)
{ print "Add hot water" }
else
{ print "Add more water" }

The For loop
You can create a loop by using a "for" loop construct (as it is known.)  The "for" statement says "for a value of x starting here, until the value of x meets this condition, and changing the value of x by this amount each time you process the loop, process this code".  This could use a little explanation!  Basically, x is going to serve as a counter.  We give x a start value, for example 1.  Then we specify a condition to test before we decide to process the block of instructions in the loop, for example x < 11.  Finally, we specify an amount by which to change x at the end of processing the block of instructions, for example, increment by 1.  In this example, the code would be run ten times, with x having a value of 1 the first time through, 2 the second, etc. The last time through it would have a value of 10.  Here's its format:
for ( counter's initial valuecounter's condition test, counter's increment )
{ do these instructions }
and here's an example
for ($count = 1; $count < 11; $count++ )
{
   $tot = 2 * $count;
   print "2 times $count equals $tot ";
}
This example prints out the two times table from two times one to two times ten.  It's worth taking special note of the fact that the test comes at the beginning of the loop -- that is, before the code block is run.  Hence the need for a test for "less than 11" in order to get the tenth iteration to run.

The "While" loop
Another loop construct is the "While" loop construct.  The for loop uses a counter to control the number of iterations of its code block, but the while loop can use any kind of condition.   There is an inherent danger here!  What happens if the condition always remains true?  The code never stops running -- that's what!  This is known as an infinite loop and the a sure sign of a programmer error.  PHP allows a system administrator to defend their system against this kind of abuse of processor time by providing a time-out mechanism.  PHP scripts are typically limited to 30 seconds of execution time, and will quit with an error at that point.  It is an important part of the debugging process to ensure that you don't wind up with any infinite loops!  That having been said.....
A "while" statement says "while this condition is true, process this code" and its format is:
while ( condition )
{ do these instructions }
Here's our two times table as a while loop:
$count = 1
while ( $count < 11 )
{
   $tot = 2 * $count;
   print "2 times $count equals $tot ";
   $count = $count + 1;
}
There is a couple of things to take particular notice of in this example.  Firstly, we had to include a separate statement to initialize the count data element because it is not part of the construct as it would be in a for statement.  Remember that the condition in a while statement can be any condition -- I have used a counter type of condition only to show the comparison of this construct to the for construct.  Secondly, and for the same reason, there has to be a statement in the code block to increment $count (I could also have used   $count++   or   $count += 1  -- I like the format I used the best because it seems the clearest to me.)
There is also a variant of the while loop that puts the test for the condition at the end, that is, after the code block has been processed.  This, of course, means that the code block will always run at least once.   This variant is the "do... while" loop and it says "do this code block, and while this condition is true, go back and do it again".  Its format is:
do
{ these instructions
}
while ( condition );
Here's our two times table as a do while loop:
$count = 1
do
{
   $tot = 2 * $count;
   print "2 times $count equals $tot ";
   $count = $count + 1;
}
while ( $count < 11 )
These options show you how you can create program execution loops in you PHP code.  Which one is the best to use depends on the particular type of execution requirement.  You have to think a it about the flow of logic as you see it, and use the construct that most closely resembles what you need.  Another thing to remember is that you can nest these constructs, by which I mean that the code block to be run by the construct could include another loop construct.  Any type of loop can be contained within any other type of loop.
When you include code within a loop like this it is a valuable thing to do to indent the code a couple of spaces like I have done in the examples above.  This is especially true when you include one loop inside another.  By the time you are two or three levels deep it is only the indentation that will show you whether or not you are missing any closing races!!  Remember that you really want to be your own best friend!

No comments:

Post a Comment

Thanks for comment me