Friday, June 19, 2009

PHP Control Structures

Conditional statements

Like many other programming languages, PHP includes several different controlstructures that can be grouped into two different areas: conditional statements and loops. In the following tutorial, I will give you some examples of each and show you when to use them. So let's start with the conditionals.

If
"If" is used whenever some PHP or HTML code needs to be executed based on one condition.

<?php
if ($myvariable == 1) print "Hello!";
?>

This means "Print the string 'Hello!' if the variable $myvariable is equal to 1" (note the double equal signs!). If you want to execute more than one line of code, just use a code block:

<?php
if ($myvariable == 1)
{
print "Hello!";
$othervariable = 2;
}
?>

In the above example, you tell PHP to "print the string 'Hello!' AND set the variable $othervariable to 2 if the variable $myvariable is equal to 1". You can even use if statements inside of other ifs if you like:

<?php
if ($myvariable == 1)
{
if ($othervariable == 2)
{
print "Hello!";
}
}
?>

This one checks if $myvariable equals 1. If this is true, it checks if $othervariable equals 2, and if this is also true, PHP will print "Hello!". There IS a better way to accomplish the above example with less code using other operators (I'll get to that in a short while) but let's first stick with other ways of using "if". So what if you want to execute other code if the given condition is NOT true? Well, just use "else":

<?php
if ($myvariable == 1)
{
print "Hello!";
$othervariable = 2;
}
else
{
print "Goodbye";
}
?>

Here, PHP will print the string "Goodbye" whenever $myvariable is something other than 1. If there are more than two code blocks you want to execute based on different conditions, you can use "elseif":

<?php
if ($myvariable == 1)
{
print "Hello!";
$othervariable = 2;
}
elseif ($myvariable == 2)
{
print "Have fun!";
}
else
{
print "Goodbye";
}
?>

So now, PHP will check if $myvariable equals 1. If it isn't, it will check if $myvariable is 2, and if it is neither 1 or 2, PHP will print "Goodbye". You see that those constructs can be very long, for example if you want your script to act differently if $myvariable is 1, 2, 3, 4, etc. A shorter way to accomplish that is using the switch statement which I will discuss in a short while. But first, let me show you the different operators that can be used inside the most important control structures (so far we only used the double equal sign "==") and a funky new way of using "if".

Operators








Let me give you a quick example for the "and", "or" and "not" operators:

<?php
if (($myvariable < 10 && $myvariable > 5) || !(
$othervariable = 1))
{
print "Yeah!";
}
?>

Can you see what that does? It means: "Print 'Yeah!' EITHER if $myvariable is less than 10 and greater than 5 OR if $othervariable is NOT equal to 1". Note that you can also write "$othervariable != 1" as the second condition. Now here's a slick little line of code for those of you who don't like long code fragments. Suppose you want to have an if statement that does this: "Check if $myvariable is 1. If that is true, change the value of $fruit to 'apple' else to 'banana'". Now that you know how to use if, you'd probably do it like this:

<?php
if ($myvariable == 1)
{
$fruit = 'apple';
}
else
{
$fruit = 'banana';
}
?>

There's another way, called the "ternary operator":


<?php
$fruit = ($myvariable == 1) ? 'apple' : 'banana';
?>

That's it! Yes, I admit, it looks wild, but once you see how it works it's nice to use. You always use it like this:

<?php
$variable =
(condition) ? 'value_if_condition_is_true' :
'value_if_condition_is_false'
?>

Switch

OK, time for "switch". Whenever you have many different code blocks that need to be executed based on different conditions of a variable, it's best to use "switch". An example? OK, here we go:


<?php
switch ($myvariable)
{
case 1:
print "One";
break;
case 2:
print "Two";
break;
case 3:
print "Three";
break;
default:
print "Other number";
}
?>

This one checks $myvariable and prints "One" if it's value is 1, "Two" if it's 2, "Three" if it's three and "Other Number" if it's something else (the "default" branch). But what about the "break;"? It stops the execution of the switch command! If you wrote the switch without the breaks, it would act differently. Check this out:


<?php
switch ($myvariable)
{
case 1:
print "One";
case 2:
print "Two";
case 3:
print "Three";
default:
print "Other number";
}
?>

So let's say $myvariable equals 2. What will happen? Well, this script will print out: "TwoThreeOther number". Can you see why? Since $myvariable equals 2, the script prints out "Two". But because we didn't input the "break" commands, it executes all other lines inside the switch, too!

Loops

Alright, time for loops! Whenever you want something done over and over, loops are the control structures of choice. One example for using loops is reading line by line from a text file. So first I'll just show you the simplest loop there is: while!

While loops

<?php
$myvariable = 0;
while ($myvariable < 10)
{
print "HELLO!";
$myvariable++;
}
?>

This one means "as long as $myvariable is smaller than ten, print out 'HELLO!' and add one to $myvariable". So this example will print out "HELLO!" ten times. If we'd set $myvariable to ten before the while loop, it would not have printed out anything. But what if we want PHP to print out at least one "HELLO!" in any case? Check this:

Do Loops

<?php
$myvariable = 10;
do
{
print "HELLO!";
$myvariable++;
}
while ($myvariable < 10);
?>

Can you see the difference? If you use a do loop, the condition (in this case
"$myvariable < 10") is checked AFTER the code within the loop has been processed
once! So in the above example, you will see one "HELLO!". Ready to look at a more
complex loop? OK, here we go!

For loops

Let's use the "HELLO!" example again:

<?php
for ($countervariable = 0; $countervariable < 10;
$countervariable++)
{
print "Hello!";
}
?>

Can you imagine what happens inside the parentheses? Right, PHP initializes $countervariable and gives it the value zero. Then it starts looping. With each loop, it is checked whether $countervariable is smaller than ten and if that is true, "HELLO!" is printed and $countervariable is increased by one! Whenever you know how many loop cycles you need, it's best to use a for loop.

Control structures in Java

We have mentioned that Java programs contain classes and that these classes contain methods which contain statements that are executed by the computer. Now we look at ways of putting statements together using control structures to organise the execution of the program. A control structure might cause a statement to be executed once, several times, or not at all. Control structures make up some of the statements of the Java language. Statements are said to be sequentially composed when they are written one after the other. Sequentially composed statements can be grouped together into a block by using the left brace and right brace symbols (“{” and “}”) to bracket them.

6.1 Assignments

An assignment statement in Java has two parts. It has a variable on the left-hand side and an expression on the right. The expression is first evaluated to yield a value. That value is then used as the new value of the variable. Here are some examples.





The equals sign is an assignment operator in Java, but it is not the only one. The op- erators *=, /=, %=, += and -= are also assignment operators, and there are still others.These operators combine the use of an operator and the execution of an assignment into a single statement. These assignment operators provide a shorthand way of ex- pressing assignment statements where the expression is used to modify the value of a variable by making use of its previous value in order to calculate the new value. Here are some examples of these kinds of assignment statements.






Other kinds of updates occur so frequently that the Java language provides short- hand versions of them. The operations of adding 1 to a variable and subtracting 1 from a variable are abbreviated as shown below.





6.2 Conditional statements

A conditional statement allows a choice from a selection of statements. It first evaluates an expression to decide between the possibilities. If there are only two then a boolean- valued expression (also called a logical expression) will be enough to allow us to choose. These can be formed using the == operator (equal to) or the != operator (not equal to). When comparing numeric values we could use the relational operators < (less than), > (greater than), <= (less than or equal to) or >= (greater than or equal to). A conditional statement uses the keywords if and else to mark the beginning of the conditional statement and to separate the two sub-statements. The first sub- statement is to be executed if the expression in the condition evaluates to true. The second sub-statement is to be executed if the expression in the condition evaluates to false. These two sub-statements are referred to as the then-statement and the else-
statement respectively. It is possible for a conditional statement not to have an else-clause. Java has both an if-then statement and an if-then-else statement. We will consider some examples.














We can picture a conditional statement graphically. We have a condition box with two exit paths, one labelled true and the other labelled false. The path labelled true leads to the “then”-statement. The path labelled false leads to the “else”-statement. After these two statements the paths meet up so that control can pass to the next statement in the program.

















All of the conditional statements which we have seen have just a single statement as the then-statement or the else-statement. When we need to perform two actions in some case then we need to bracket them together with left and right braces. Without these the effect is quite different.







When formatting computer programs we will normally use blank-space indentation toconvey hints to the reader about statement structure. However, as far as the compilerfor the Java language is concerned, one blank space is as good as ten so the differenteffect of the two statements is achieved by the use of the left and right braces, and not by the blank-space indentation at the start of the line.

6.2.1 Reserved words

The words “if” and “else” are reserved words in Java but the word “then” is not. A reserved word is used to mark out a particular kind of statement and cannot be used as an program identifer (this is the sense in which it is reserved). Throughout these notes we will format reserved words in bold typewriter font.

6.3 The switch statement

A conditional statement contains a boolean-valued expression. Sometimes the expres- sion which we need to examine is an integer or a character. In this circumstance we can use a switch statement. The switch statement introduces four new keywords, switch, case, default and break. The following example is very similar to the second and third examples of conditional statements which we saw.






Without the break statements the flow of control falls through the statement so thatthe first matching statement is executed and then all of the statements which follow it. Since this is rarely useful, a switch statement almost always has a break statement at the end of each case. In the example shown above we have only one case treated specially in the switch. We could have more. The if-then-else statement allows to choose between two possible sub-statements but the switch allows us to choose between any number of them. The other cases also appear in the body of the switch statement with the default case coming at the end.

6.3.1 Contrasting “switch” with “if-then-else”

The switch and conditional statements perform related tasks, but they are not inter- changeable. One reason for this is that Java does not allow the programmer to write boolean literals as expressions on the limbs of the switch. This means that although we can think of a conditional statement as being like a switch on the value of a boolean expression, we cannot express this in Java. Supporting this separation between “switch” and “if-then-else” is the fact that Java treats boolean values as different from integer values. A boolean variable in Java can hold only the value true or the value false. An integer variable can hold negative or positive integers.

6.4 Iteration

The statements which we have seen so far allow selective execution of statements. To express repetitive execution of statements we use another construct, Java’s while statement. A while statement is often called a loop. A while loop contains a boolean- valued expression which is known as its test (or sometimes its condition or sometimes its guard). It also contains a statement which is the body of the loop. The first thing to happen is that the boolean expression is evaluated. If it evaluates to false then the body of the loop is not executed at all and the flow of control can pass to the next statement in the program. If it evaluates to true then the loop body is executed, and then the test is redone to see if the loop body is to be executed again (this is the “looping” part), and this continues in this way until the test eventually evaluates to false and the flow of control can then finally pass on to the next statement in the program. Here is a simple program fragment which prints out messages while decreasing the value of x. After it has finished it prints a message to report this.

while (x > 0) {
System.out.println("decreasing");
x--;
}
System.out.println ("finished");

If we executed such a code fragment when the variable x held the value 3 then we would see the following results:

decreasing
decreasing
decreasing
finished

The two statements which come between the open brace and the close brace are the body of the loop. The body is repeatedly executed while the loop condition (x > 0) is true. There is a possibility that the loop body will never be executed at all. If the value of x was zero or less upon reaching the while statement then the loop body will not be executed. In general with a while loop the body is executed zero or more times. As with the conditional statement, a while loop can be pictured in a diagram. Sim- ilarly to the conditional statement again, a while loop has a boolean-valued condition at the top. The result of this expression determines which statement will be executed next. The picture is slightly more complicated because of the need to loop back to repeat the test after the loop body has been completed.




















6.4.1 An example: computing prime factors

A more intricate use of the while loop is shown below. The program fragment below prints the prime factors of x. The prime factors of a number are those primes which can be multiplied together to give the number. For example, 3 and 5 are prime numbers and 3, 3, 3 and 5 are the prime factors of 135.

int d = 2; // set d to 2
while (x != 1) { // stop when we reach 1
while (x % d == 0) { // while d divides x
System.out.println(d); // report d
x /= d; // divide by d
} //
d++; // move on
}

Compared to the program fragments which we have seen so far in these lecture notes, this is a very complicated example. We have a while loop with a while loop inside it. We sometimes describe this as a nested loop: the inner loop nested in the outer one.