Home arrow PHP arrow Page 5 - The PHP Scripting Language

switch Statement - PHP

This article describes the basics of the PHP scripting language, which is very easy to learn if you are familiar with any programming language. It is excerpted from chapter two of the book Web Database Applications with PHP and MySQL, written by Hugh E. Williams and David Lane (O'Reilly, 2004; ISBN: 0596005431).

  1. The PHP Scripting Language
  2. Creating PHP scripts
  3. Character encoding
  4. Expressions, Operators, and Variable Assignment
  5. switch Statement
  6. Changing Loop Behavior
  7. Automatic Type Conversion
  8. User-Defined Functions
  9. Static variables
  10. Managing include files
By: O'Reilly Media
Rating: starstarstarstarstar / 32
September 29, 2005

print this article



The switch statement can be used as an alternative to if to select an option from a list of choices. The following example executes different code for different integer values, or cases of the variable $menu. Acaseclause is provided for values 1, 2, 3, and 4, with adefault: case provided for all other values:

switch ($menu)
case 1:
print "You picked one";
case 2:
print "You picked two";
case 3:
print "You picked three";
case 4:
print "You picked four";
        print "You picked another option";

This example can be implemented withifandelseif, but theswitch method is usually more compact, readable, and easier to type. The use ofbreakstatements is important: they prevent execution of statements that follow in theswitch statement and force execution to jump to the statement that follows the closing brace.

Ifbreakstatements are omitted from aswitchstatement, you can get an unexpected result. For example, without thebreakstatements, if the user chooses option 3, the script outputs:

You picked three. You picked four. You picked another option

These results are often a source of difficult-to-detect bugs; however, by intentionally omitting thebreakstatement, you can group cases together as shown in the followingswitchstatement:

$score = "Distinction";
switch ($score)
case "High Distinction":
   case "Distinction":
print "Good student";
case "Credit":
case "Pass":
print "Average student";
      print "Poor student";

While not mandatory, thedefault: case is useful when default processing is performed on all but selected special cases, or to handle unexpected values when expected values have corresponding cases.

Conditional Expressions

Now we’ll look at what can go inside the parentheses of an if statement, and other control statements. The most common conditional comparison is to test the equality or inequality of two expressions. Equality is checked with the double-equal operator, == ; if the value on the left-hand side is equal to the value on the right-hand side, then the expression evaluates to true. The expression($var == 3)in the following example evaluates to true:

$var = 3;
if ($var == 3)
    print "Equals 3";

Inequality is tested with the not-equals operator,!=. Both evaluate to a Boolean result oftrueorfalse.

If the equality operator == and the assignment operator = are unfamiliar, beware: they are easy to inadvertently interchange. This is a very common bug and hard to detect.

The value of the conditional expression ($var = 1) evaluates as true, because the expression takes its value from the value on the right hand side of the assignment operator; in this case 1. Here is an example of a common mistake, which overwrites the original value of the variable and always prints the statement:

if ($var = 1)
 print"Variable equals 1.";

The error of incorrectly replacing an assignment with == is a far less common mistake. However, it’s also difficult to detect because an incorrectly written assignment of$var == 1;is quietly evaluated as true or false with no effect on $var.

Expressions can be combined with parentheses and with the Boolean operators&&(and) and||(or). For example, the following expression returns true and prints the message if $var is equal to 3 or $var2 is equal to 7:

if (($var == 3) || ($var2 == 7))
   print "Equals 3 or 7";

The following expression returnstrueand prints the message if$varequals 2 and$var2equals 6:

if (($var == 2) && ($var2 == 6))
   print "The variables are equal to 2 and 6";

Interestingly, if the first part of the expression($var == 2)evaluates asfalse, PHP doesn’t evaluate the second part of the expression($var2 == 6), because the overall expression can never betrue; both conditions must betruefor an&&(and) operation to betrue. Similarly, in the previous example, if($var == 3), then there’s no need to check if($var2 == 7).

This short-circuit evaluation property has implications for design; to speed code, write the expression most likely to evaluate asfalseas the left-most expression, and ensure that computationally expensive operations are as right-most as possible.

Never assume that expressions combined with the Boolean operators&&and||are evaluated. PHP uses short-circuit evaluation when determining the result of a Boolean expression.

Conditional expressions can be negated with the Boolean not operator !. The following example shows how an expression that tests if$varis equal to 2 or 6 is negated:

if (($var == 2) || ($var == 6))
   print "The variable var is equal to 2 or 6";
if (!(($var == 2) || ($var == 6)))
   print "The variable var is not equal to 2 or 6";

Unlike the&&and||operators,!works on a single value as the following example highlights:

// Set a Boolean variable
$found = false;
// The following message is printed
if (!$found)
print "Expression is true";

More complex expressions can be formed through combinations of the Boolean operators and the liberal use of parentheses. For example, the following expression evaluates astrueand prints the message if one of the following istrue: $varequals 6 and$var2equals 7, or$varequals 4 and$var2equals 1.

if ((($var == 6) && ($var2 == 7)) || (($var == 4) && ($var2 == 1)))
   print "Expression is true";

As in assignment expressions, parentheses ensure that evaluation occurs in the required order.


Loops add control to scripts so that statements can be repeatedly executed as long as a conditional expression remains true. There are four loop statements in PHP: while, do...while,for, andforeach. The first three are general-purpose loop constructs, while the foreach is used exclusively with arrays and is discussed in the next chapter.


The while loop is the simplest looping structure but sometimes the least compact to use. The while loop repeats one or more statements—the loop body—as long as a condition remains true. The condition is checked first, then the loop body is executed. So, the loop never executes if the condition isn’t initiallytrue. Just as with theifstatement, more than one statement can be placed in braces to form the loop body.

The following fragment illustrates thewhile statement by printing out the integers from 1 to 10 separated by a space character:

$counter = 1;
while ($counter < 11)
print $counter . " ";


The difference between while and do...while is the point at which the condition is checked. In do...while, the condition is checked after the loop body is executed. As long as the condition remainstrue, the loop body is repeated.

You can emulate the functionality of the previouswhileexample as follows:

$counter = 1;
print $counter . " ";
} while ($counter < 11);

The contrast betweenwhileanddo...whilecan be seen in the following example:

$counter = 100;
print $counter . " ";
} while ($counter < 11);

This example outputs 100, because the body of the loop is executed once before the condition is evaluated asfalse.

Thedo...whileloop is the least frequently used loop construct, probably because executing a loop body once when a condition isfalseis an unusual requirement.


The for loop is the most complicated of the loop constructs, but it also leads to the most compact code.

Consider this fragment that implements the example used to illustratewhileanddo...while:

for($counter=1; $counter<11; $counter++)
   print $counter;
print " ";

Theforloop statement has three parts separated by semicolons, and all parts are optional:

Initial statements

Statements that are executed once, before the loop body is executed.

Loop conditions

The conditional expression that is evaluated before each execution of the loop body. If the conditional expression evaluates as false, the loop body is not  executed.

End-loop statements

Statements that are executed each time after the loop body is executed.

The previous code fragment has the same output as ourwhile anddo...whileloop count-to-10 examples.$counter=1is an initial statement that is executed only once, before the loop body is executed. The loop condition is$counter<11, and this is checked each time before the loop body is executed; when the condition is no longertrue(when$counterreaches 11) the loop is terminated. The end-loop statement$counter++is executed each time after the loop body statements.

Our example is a typicalforloop. The initial statement sets up a counter, the loop condition checks the counter, and the end-loop statement increments the counter. Mostforloops used in PHP scripts have this format.

Conditions can be as complex as required, as in anifstatement. Moreover, several initial and end-loop statements can be separated by commas. This allows for complexity:

for($x=0,$y=0; $x<10&&$y<$z; $x++,$y+=2)

However, complexforloops can lead to confusing code.

>>> More PHP Articles          >>> More By O'Reilly Media

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: