[main] [misc] [graphics] [page design] [site design] [xhtml] [css] [xml] [xsl] [schema] [javascript] [php] [mysql]

HVCC Home
Blackboard HVCC
Blackboard Manual
Faculty Association

php main
1. what is php
2. http basics
3. php basics
4. php expressions
5. php client side
6. php flow control
* a. php conditionals
b. php adv conditions
c. php iteration
d. php functions
e. php adv functions
f. php modularity
7. php manual


print version

Note that all external links will open up in a separate window.

This is a stripped down version of these pages for older browsers. These pages are really meant to be viewed in a standards compliant browser.

Directions for surfing with audio.

Conditionals

These tutorials are about PHP and its use for server-side Web programming.

Conditionals

Some statements in PHP are known as conditional statements. These statements make use of statements that delimit them and which determine whether or not the delimited code is executed, based on some condition.

We will look at two structures here

  • the if statement
  • the switch statement

We will also look at some alternative methods for coding both statements (PHP likes to be flexible).

The if Statement

In most C-style languages, there are two basic conditional statements, the if statement and the switch statement (also sometimes called the case statement). PHP is no exception.

We are going to start with the if statement. It is the easier of the two.

The if statement is a simple concept. If something is true, then perform the statement block associated with it, otherwise don't. To use conditionals, you need to be evaluating an expressions that evaluates to true or false. We have discussed conditional operators elsewhere, but we can also test for non-zero, non-null, non-empty values in variables, and many system defined functions return true or false depending on their successful execution.

The if statement takes the form of

if (conditional expression) {
  statement block;
  }

Some programming languages make use of the then keyword (if ... then). PHP does not.

If some conditional expression evaluates to true then PHP performs the associated statement block. For instance, the following statement will echo out a warning that the value of a variable is not an integer. It will only generate this message if the expression !is_int($x) evaluates to true, which is to say, if it is not a number.

if (!is_int($x)) {
  echo ($x . ' is not an integer!');
  }

If you just want to execute a single statement within an if statement, you do not technically need the curly brackets, but they are a good habit to get into so you don't forget them.

The else Statement

The if statement executes a block of code if something is true.

What happens if you want to execute one block of code if something is true and another if it is false? In this case, PHP has something called the else statement.

The else statement can only follow an if statement and is used to mark off a statement block to execute if the conditional expression being tested evaluates to false. It does not take its own test condition expression because it executes in response to the if statement immediately preceeding it returning false.

if (!is_int($x)) {
  echo ($x . ' is not an integer!');
  }
else {
  echo $x . ' is a number we can work with!');
  }

Don't forget the curly brackets around both expression blocks. Thinking that the else is part of the if statement (which technically it is) makes it easy to forget to close the if statement block before the else statement block.

The elseif Statements

What happens if you want to test for more than simply whether a given expression equates to true or false, but want to test for and execute code based on a variety of possible conditions? Which is to say, what happens if there are three or more conditions.

PHP has an elseif statement. This allows us to test for another conditions if the first one wasn't true. The program will test each condition in sequence until:

  • It finds one that is true. In which case it executes the code for that condition.
  • It reaches an else statement. In which case it executes the code in the else statement.
  • It reaches the end of the if ... elseif ... else structure. In this case it moves to the next statement after the conditional structure.

The elseif sturcture looks like this:

if (is_int($x)) {
  echo ($x . ' is an integer');
  }
elseif (is_float($x)) {
  echo ($x . ' is a floating point number');
  }
elseif (is_string($x)) {
  echo ($x . ' is a string');
  }
elseif (is_bool($x)) {
  echo ($x . ' is a boolean');
  }
else {
  echo ($x . ' is not a primitive data type');
  }

The switch Statement

Although you can test for multiple conditions with a series of if statements, the if statement really does only test the truth of a single conditional expression at a time. It is a two state expression, either the statement block executes or it doesn't.

If you want to check a single variable for multiple values, you can do so with a series of if statements, but this is not always the best approach. PHP also provides a conditional statement for testing multiple values for a single variable or expression. This is the switch statement.

The switch statement, in its structure, is similar to the if statement. It takes an expression to be evaluated and a statement block.

The switch statement can only evaluate a single expression, but it can compare that single expression to a series of possible values. The expression to be evaluated is most likely not a conditional, since a conditional only has two possible states -- something best handled by an if ... else statement. Rather it is usually some expression that can have a series of values, such as a variable that can have a number between 0 and 9, or a form field that can contain one of the fifty two-character abbreviations for the U.S. state names.

switch (expression) {
  statements;
  }

Although the shell of the statement is the same, the body of the statement block is significantly more complex and requires additional keywords to make the statement work. A full switch statement may look like the following example.

switch ($myState) {
  case "NY":
    echo "You're from New York";
    break;
  case "VT":
    echo "You're from Vermont";
    break;
  case "MA":
    echo "You're from Massachussetts";
    break;
  default:
    echo "You're not from around here";
    break;
  }

Let us look at the various elements.

The case Statement

label: in programming, an identifier in the code used to assign a name to that specific location in the code

The case keyword is a label, it marks a point in the code to do something. Specifically it marks the point in the code to begin executing statements if the value of the expression being evaluated by the switch statement is equal to the value immediately following the case keyword or if the expression following the case keyword evaluates to true. The colon marks the end of the label. The entire label should be on one line.

In PHP, the case statement takes an expression which must equate to true for the following code to be run. If you are doing simple equality then you can just provide the value you are checking for and it assumes that the expression is testing the switch expression against the value in question for equality. However, by allowing expressions, you can also test for other conditions, such as greater than and less than relationships. When using expressions, the expression you are testing against must be repeated in the case statement.

switch ($someNumber) {
  case 0:
    echo "Zero is not a valid value.";
    break;
  case $someNumber < 0:
    echo "I can't use negative numbers.";
    break;
  default:
    echo "Ready to compute.";
    break;
  }

If an expression successfully evaluates to to the values specified in more than one case statement, only the first one encountered will be executed. Once a match is made, PHP stops looking for more matches.

In the following case, the second case will never be executed, because anything greater than 1000 is also greater than 100.

switch ($someNumber) {
  case $someNumber > 100:
    echo "The number is greater than 100.";
    break;
  case $someNumber > 1000:
    echo "The number is greater than 1000.";
    break;
  }

The way around this is just to make sure that the conditions are specified in the correct order for what you want them to do.

switch ($someNumber) {
  case $someNumber > 1000:
    echo "The number is greater than 1000.";
    break;
  case $someNumber > 100:
    echo "The number is greater than 100.";
    break;
  }

The default Condition

The default keyword is a catch-all case that marks the point to begin execution of none of the conditions being tested for are met. It is like the last else statement in a long string of elseif's.

Like the last else, it should always appear at the end of the switch statement, since it will always be executed if no previous match has been made, and since PHP stops lookng when it finds a match. default is always a match if it is reached. You should only use it if you have code that is to be run if none of the conditions are met. For instance, error code to report that the expression did not evaluate to an expected value.

The break Statement

The break keyword is a statement that says that we are done performing statements within this statement block and that we should exit immediately to the end of the statement block. If you forget the break statement, then the code will fall through, which is to say that the code will start executing at the label that matches the value of the expression being evaluated, and then will proceed to process all code until either the end of the switch statement or until it find a break statement, which ever comes first. If done intentionally, this can be useful. If done by mistake it can be a real problem.

Here is a good use of omitting break statements. It allows use to perform the same black of code for multiple possible values of the expression being evaluated.

switch ($xyz) {
// each of these three cases
// will process the same statements
  case $xyz < 0:
  case 0:
  case 10:
    echo ($xyz . ' is not a value I can work with!');
    break;
  default:
    echo ($xyz . ' is ready for processing!');
    $abc = someFunc($xyz);
    break;
  }

Here is a bad example of omitting break statements. The code will fall through and create a bit of a mess.

// A poorly formed switch statement
switch ($xyz) {
  case is_int($xyz) == false:
    echo ($xyz . ' is not an integer!');
  case $xyz <= 0:
    echo ($xyz . ' is too low!');
  case $xyz >= 10:
    echo ($xyz .+ ' is too high!');
  default:
    echo ($ xyz . ' is within acceptable limits!');
    $abc = someFunc($xyz);
    break;
  }

If we assume for right now that $xyz is not an integer:

  1. The code will report that $xyz is not an integer.
  2. Then report that it is too low a number.
  3. Then report it is too high.
  4. Then it report that it is an acceptable value.
  5. Then it will submit it to our function, which we can surmise from the code was expecting a numeric value between 1 and 9, not something else. This, needless to say, would most probably generate an error.

Unless your goal is to confuse the user, what you would have is what is called a big mess.

The break statement can also be used in an odd way in PHP that can cause errors if you are not aware of it. If the break statements is the only statement following a given case statement, the code will skip to the default statement block instead of the end of the switch statement.

This may seem a little odd for experienced programmers because it raises the question, why include a separate case statement for case statement for something that should fall into the default. The primary reason is that it allows you to exclude certain values that might otherwise meet a later condition. For instance, if we go back to our previous example and wanted to code to run the default statements for a number between zero and nine or for any number divisible by 10, we could code:

switch ($xyz) {
  case is_int($xyz) == false:
    echo ($xyz . ' is not an integer!');
    break
  case $xyz <= 0:
    echo ($xyz . ' is too low!');
    break
  // the following statement will skip to
  // the default
  case $xyz % 10 == 0:
    break;
  case $xyz >= 10:
    echo ($xyz .+ ' is too high!');
    break
  default:
    echo ($ xyz . ' is within acceptable limits!');
    $abc = someFunc($xyz);
    break;
  }

Other Formats

PHP likes to cover its bases, so it provides alteranate methods for coding if statements and switch statements.

Alternate if

There are two alternate ways to code an if statement, one is a ternary operator, one is an alternate syntax.

The ternary operator takes the form of:

(condition) ? value_if_true : value_if_false;

$hours = ($hours < 13) ? $hours : $hours -= 12;

Since the ternary operator is, in fact, an operator, it returns a value, which is the value of one of the expressions. If the condition evaluates to ture, then the first value is returned (value_if_true), otherwise the second value is returned (value_if_false). This means that the expressions for the true and false values need to be things that evaluate to values, not full blown statements, just simple expressions.

The alternative sytax makes use of labels for all components of the if statement. The curly brackets are omitted. Since there are no curly brackets, there needs to be some way to specify the end of the statement block. For this we use and endif label.

The code looks like this:

if (condition):
  statements;
elseif (condition):
  statements;
else:
  statements;
endif;

if ($x < 0):
  echo "Can't use a negative number.";
elseif ($x > 999999):
  echo "Can't use that big a number.";
else:
  doSomethingWith($x);
endif;

Aternate switch

The alternate switch statement has the same syntax as the alternate if statement. The curly brackets are omitted and a closing endswitch is used to denote the end of the statement block.

switch ($someNumber):
  case 0:
    echo "Zero is not a valid value.";
    break;
  case $someNumber < 0:
    echo "I can't use negative numbers.";
    break;
  default:
    echo "Ready to compute.";
    break;
endswitch;

[top]