PHP Control Flow Overview

Feature: Control of Flow in PHP
Credit: Imagenation, PHP Documentation Group

PHP starts with many strengths in its logical and bitwise operators. PHP then extends the ideas of C, Java and Perl control of flow and looping functionality - giving them more of the ease of use associated with Visual Basic or Ruby. Also enhancing the functionality of its associative array, PHP has some powerful control commands with list(), each() and foreach().

Finally, PHP takes full advantage of its mixed type capability for variables and functions. Thus functions like fopen() return a value (a file handle in the case of fopen() finding a file for opening) or the Boolean false if no file was found. Developers have to be alert to these different


The Control of Flow Commands

break In PHP break is a terminator of loops. break ends execution of the current for, foreach, while, do..while or switch structure. break accepts an optional numeric argument which tells it how many nested loops are to be broken out of.

do statement while(test);
while(test) statement;
while(list($k,$v)=each(array))
  statement ;
do..while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of at the beginning. The main difference from regular while loops is that the first iteration of a do..while loop is guaranteed to run; not so for a while whose statements may not be run at all if test is false.
The foreach command simplifies even more the while powerhouse

if (test) statement;
if (test){ ..statements; }
if (test) statement else statement;
if (test): statement;
   [elseif(test): statement;]
   [ else: statement;]
if (test){ ..statements;}
   [elseif(test){
    ..statements;} ]
   [else {..statements;}]

if statements in PHP are fully powered. Note new colon syntax for bracketing simple , one statement ifs.

Developers can use a string of elseif conditional continuations; they can use brackets, {..statements;}, to contain blocks of statements or they can use the simple one statement conditional.

ternary operator:
(test)? expression : expression2;

Some people like it; others don't.
$color = ($cnt++ % 2)? "aqua" : "green";

switch (expression){
  case value-1: case alternate-value:
    [..statements;] [break;]
    ...
  case value-n:
    [..statements;] [break;]
  [default: [..statements;]]
}

We have highlighted case alternate-value: for 2 reasons.
1) alternate-values: can be an expression not a single value
2)Being able to stack up several alternate values is supremely useful in option-rich event loops, parsing, message passing, etc.

 for (expr1; expr2; expr3) statement; The classic for-loop from C, Java and Perl - expr1 is evaluated once at start of loop; expr2 is evaluated at start of loop and if True then statement (which may be a { statement; ...} -a block of statements) is executed; finally if the loop is not broken out of (see break) expr3 is evaluated at the end just before looping back and checking with expr2 if the loop is to be done again. Simple.
foreach(arrayexp as $value) statement;
foreach(arrayexp as $key => $value) statement;

 The foreach clause is a classic borrow from Perl (and C# will be doing the same shortly). It is tailored for use with associative arrays. The first form enumerates all the different $value in arrayexp. The second form initializes both $key and $value during the enumeration of the assciative arrayexp. The foreach $key=>$value has been extended in PHP 5 to allow enumeration of all the public properties or variables of an object.

in PHP because they are used all over - especially in for loop clauses where False ends the loop.

As can be seen PHP has very versatile control of flow commands. All of the same commands of C and Java but with more options as in Perl and Visual Basic. These days where ease of programming are paramount - relaxing the constraints in loop structure which is comparatively easy to optimize underneath in the compiler/interpreter is a big win for developers.

The following are examples of the different control loops. Just use CTL+A to select the code and CTL+C to copy it into your favorite editor for testing

Local Testing of PHP Code

It is fairly simple to test PHP code on your local machine. Some of the code in the text box to the left has been used in a test routine shown in the figure below. This routine has not been run on a server but instead "locally" on an Apache Web server installed on our local machine with PHP 4.1.2 also installed there. Having your own Web Server (be it IIS or Apache) and acopy of PHP allows developers to configure the settings of the the web server and PHP to whatever is required for various software applications and testing purposes. I often use it as a test of proper software setup - if the code runs on the local machine then there maybe be a problem or

difference in configuration between the client web server setup and my local machine that I am not aware of - but at least I know the problem is in the setup - not the underlying code.

It is also useful to maintain different copies of Apache, Java, PHP and PERL. Two versions - the bleeding edge which uses the latest development versions and production stable again allows for checking out code that suddenly does not work. Unfortunately, Open Source's rapid maintenance and new features rate of development also rears its ugly head in terms of backward incompatibility problems.

Having said this, it simply is not necessary to have a local and two copies of a web server or system. Apache and Java in particular have been very good about warning of deprecated and soon-to-be obsoleted commands and functions. However, when major updates like PHP 5 and Perl 6 and Apache 2 come down the pike it is nice to be prepared for teething problems.

  Top of Page  Home   Tips & Tutorials
© Imagination 2001-2004