Control Structures

Under normal conditions, an execution engine like the PHP always executes code instructions on a line-by-line basis. That is, it performs the first statement, then the second statement, etcetera, until the last statement. A program like this would not be really be doing any useful application.


Through the use of control structures, you can interrupt the normal line-by-line flow of program execution allowing other instructions to be performed and skipping the others. By doing this,you are essentially giving the computer the ability to think and decide. Control Structures can also save you time is doing repeatitive statements. In this tutorial we will explore how control structures are formed in PHP. As usual, if you have a background on C, Java or C#, you will find the PHP equivalent to be very much alike.

In the code snippets that follow, I have made a few notations to get my point across.

c = condition
c1 = first condition
c2 = second condition
...
cn = nth condition

s = statement
s1 = first statement
s2 = second statement
...
sn = nth statement

x1 = first expression
x2 = second expression
...
xn = nth expression

And 'statement' here also means a block of statements within the curly braces { } symbols.

The Decision Structure -- allows for conditional execution of code.

A. If, If-Else, If-ElseIf Structure

 if (c1)
    s1;
 [elseif (c2)
    s2;
    ...
  elseif (cn)
    sn;
  else
    default-statement;
 ]

Alternative Syntax:

 if (c1) :
    s1;
 [elseif (c2) :
    s2;
    ...
  elseif (cn):
    sn;
  else :
    default-statement;
 ]
 endif;

Items in square brackets [] are optional. More on the if structure and its alternative syntax can be found in the PHP Manual.

Some notes on using the alternative syntax:

  • There is a colon (:) at the end of the every condition
  • There is a colon (:) at the end of the else clause
  • A statement block need not have parenthesis
  • It syntax is concluded with endif; -- notice the semi-colon

Sample Code:

PHP:
  1. <?php
  2.     $x = -5;
  3.     if ($x <0 ){
  4.         print "$x is negative";
  5.     }elseif ($x == 0){
  6.        print "$x is zero.";
  7.     }else{
  8.        print "$x is positve";
  9.     }
  10.    
  11.     print "<br/>Using altertive syntax<br />";
  12.      
  13.     if ($x % 2 == 0):
  14.        print "$x is an even number";
  15.     else :
  16.       print "$x is an odd number";
  17.     endif;
  18. ?>

The alternative syntax is helpful when mixing HTML Tags and PHP Scripts in one file.

B. Switch Case Structure

 switch (c){
    case x1 : s1; break;
    case x2 : s2; break;
    case xn : sn; break;
    default : default-statement; break;
}

Alternative Syntax:

 switch (c):
    case x1 : s1; break;
    case x2 : s2; break;
    case xn : sn; break;
    default : default-statement; break;
endswitch;

Switch is like a series of if-elseif structure writen in easy-to-read format. The Online Manual has a very good explanation on the swith syntax.

Loops -- used for repeatitive tasks.

C. while Loop

 while (c)
     s;

Alternative Syntax:

 while(c)
    s;
 endwhile;

The while Loop repeats the statements contained in its body as long as the condition is true. Before executing the statement, it first tests for the value of the condition.

D. do-while Loop

 do
     s;
 while (c);

The do-while Loop repeats the statements contained in its body until the condition is becomes false. This is a post-test loop. This means that the statement is first executed prior to testing the condition. Therefore, you can be sure that the statement is executed at least once.

E. for Loop

 for ( initialization; condition;increment )
     s;

The for Loop is really a variation of the while loop. It collects together the initilization, condition and increment (or decrement) in one short block. It is ideally suited for tasks where the number of iterations is predetermined.

PHP:
  1. <?php
  2.     print "<h1>Counting with PHP Loops";
  3.     $startNum = 1;
  4.     $endNum = 10;
  5.  
  6.     print "<h2>Using the while Loop</h2>";
  7.     print '<p>';
  8.     $i = $startNum;
  9.     while ($i <= $endNum){
  10.           print "i is $i";
  11.           print "<br/>";
  12.           $i++;
  13.     }
  14.     print '</p>';
  15.  
  16.     print "<h2>Using the do-while Loop</h2>";
  17.     print '<p>';
  18.     $i = $startNum;
  19.     do {
  20.           print "i is $i";
  21.           print "<br />";
  22.           $i++;
  23.     }while ($i <= $endNum);
  24.     print '</p>';
  25.    
  26.     print "<h2>Using the for  Loop</h2>";
  27.     print '</p><p>';
  28.     for ( $i = $startNum; $i <= $endNum; ++$i ){
  29.           print "i is $i";
  30.           print "<br/>";
  31.     }
  32.     print '</p>';
  33.  ?>

F. foreach Loop

The foreach loop is ideal for processing array elements.

Syntax for getting the value of each array element:

 foreach (array as $value)
    s;

Syntax for getting the key and the value of each array element:

foreach (array as $key => $value)
    s;

This is very handy and it deserves an actual example.

PHP:
  1. <?php
  2.     print "<h1>Array with foreach Loops";
  3.     $contacts = array('Anne', 'Jesse', 'Toni');
  4.    
  5.     print "<h2>My Contacts</h2>";
  6.     print '<p>';
  7.     foreach ($contacts as $c){
  8.         print $c . '<br />';
  9.     }
  10.     print '</p>';
  11.  
  12.     print "<h2>Contacts with Numbers</h2>";
  13.     print '<p>';
  14.     foreach ($contacts as $k => $v){
  15.         print "$k :: $v<br />";
  16.     }   
  17.     print '</p>';
  18. ?>

That's about it. It's really very simple. For now, it would help if you research a bit about the operators in PHP. Refer to the PHP Manual and read about the break and continue statements.

Contact me if you need some clarifications.

Your Assignment:

Here is a fun exercise for you to do. The code below is not complete. Provide the missing code so that it displays a 5 by 10 Multiplication Table.

PHP:
  1. <?php
  2.     $rows = 5;
  3.     $cols = 10;
  4.  
  5.     print "<h1>$rows x $cols Multiplication Table";
  6.  
  7.     for ($r = 1; $r <= $rows; ++$r){
  8.          // continue your code here... or somewhere else.
  9.          // it shoud display a multiplication table
  10.     }
  11. ?>

Happy PHP Coding!

This series of articles is intended as a Self-Paced Introductory tutorial on PHP.

One Response to “Control Structures”

  1. Blogging from Experience » Archives » Form Handling with PHP Says:

    […] In tutorial, you will learn how to handle HTML forms in PHP. I am assuming that you are thoroughly familiar with creating HTML Forms. Can you do it by hand without the aid of and HTML Editor? If not, be nice to your self and fire-up that DreamWeaver Icon you placed on your desktop and get ready to rock and roll. Let us begin the discussion by trying to solve the Multiplication Table Problem mentioned in the prior tutorial on PHP Control Structures. We’ll allow the user to enter two numbers, one for the row and another for the column and then generate the Multiplication Table when he clicks on the Submit Button. Here is how the form looks like. […]

Leave a Reply

Get notified of occasional articles posted on this blog.

Enter your email address:

Delivered by FeedBurner