Session-2-Loops & Arrays
Session-2-Loops & Arrays
Conditionals
IF statements
We can use an IF statement to make a decision for a specific condition. If the condition is
true then a piece of code should be executed. Here’s an example:
if ($totalQuantity == 0)
{
echo “You haven’t chosen any product yet!”;
}
Here the condition is: "if the variable $totalQuantity equals zero …". If this condition is true
then print “You haven’t chosen any product yet!”.
If $totalQuantity is not zero, then the condition is false and the code in the curly brackets {}
will not be executed.
Note the operator "==" which is different to the assignment operator "=".
IF/ELSE statements
Often you’ll not only want to decide what to do if a condition is true, but also what to do if the
condition is false. That’s where the else statement comes in. Here’s an example:
if ($totalQuantity == 0)
{
echo "<font color = 'red'>You haven’t chosen any product
yet!</font>" ;
}
else
{
echo "You’ve chosen: ".$productName."<br>";
echo "Quantity: ".$totalQuantity."<br>" ;
echo "Price: ".$productPrice."<br>" ;
echo "TOTAL: ".$totalPrice."<br>" ;
}
Assuming the variables $productName, $totalQuantity, $productPrice and $totalPrice have
been initialised, they will be displayed. Here’s a working example:
www.ucl.ac.uk/efrei/laqua/session2/ifElse.php
(See www.ucl.ac.uk/efrei/laqua/session2/ifElseCode.txt for the PHP Code)
ELSEIF statement
Often there are more options in a decision. You can use the elseif statement to create a
sequence of options. As the name suggests the elseif statement is a combination of an else
and an if statement. Here’s an example of how you can use it:
if ($totalQuantity == 0)
{
echo "You haven't chosen anything yet!" ;
}
elseif ($totalQuantity < 10)
{
$disount = 0;
}
elseif ($totalQuantity >= 10 && $totalQuantity <= 49)
{
Introduction to Web Applications – IT Session 2
$disount = 10;
}
elseif ($totalQuantity >= 50)
{
$disount = 15;
}
So here we offer the customer a discount depending on how much he buys. The discount is
set as follows
$totalQuantity is less than 10 – no discount
$totalQuantity is larger/equal to 10 AND smaller/equal to 49 – discount = 10
$totalQuantity is larger/equal to 50 - discount = 15
SWITCH statements
Now if you have many options, it becomes a bit cumbersome to write loads of ifelse
statements. The switch statement works in a similar way, but allows the condition to take
more than two values (not just true and false). In a switch statement the condition can take
any number of values as long as it evaluates to one of the simple data types (integer, string or
double). Here's an example:
$country = "England";
switch ( $country )
{
case "France":
echo "France";
break;
case "Germany":
echo "Germany";
break;
case "England":
echo "England";
break;
default:
echo "This is not a European country";
break;
//I know there are more countries in Europe than those 3 ;o)
}
Here the statement checks what the $country variable evaluates to. If it doesn't find any of
the options, it uses the default section. Once it reaches the break statement it jumps out of
the block of code and continues after the curly brackets {}.
Loops
Often some information needs to be presented repetitively in a slightly altered way until some
condition is fulfilled. PHP allows you to use loops in order to do this.
Here’s an example:
www.ucl.ac.uk/efrei/laqua/session2/loops.php
(See www.ucl.ac.uk/efrei/laqua/session2/loopsCode.txt for the PHP Code)
Although repeating the same message might seem a bit pointless, this is just an example to
illustrate what you can do with a loop. Loops are often used to create drop down menus in
HTML forms or displaying data from mySQL (or other) databases. They are also useful for
repetitive tasks such as coding rows of HTML tables (more on that later). Basically loops
allow a form of automation that makes handling dynamic content more efficient.
Introduction to Web Applications – IT Session 2
In the above example we wrapped a loop around a statement, such as this:
<?php
$i = 0;
while ($i < 10)
{
echo "$i Hello World!<br>";
$i++;
}
?>
This code displays the message “Hello World” ten times.
WHILE - loops
The above example is a while-loop. It repeats whatever is inside it until a certain condition is
fulfilled. In the above example the condition is “Do whatever is within the loop as long as $i is
smaller than 10”.
During each execution of the loop $i gets incremented ($i++). Once it has run ten times
and $i now becomes 10, the loop is not executed anymore.
The easiest way to understand how this works is to go through the code line by line like a
computer would.
When PHP parses the above code it sees the following:
1) $i is initialised to an integer value of 0 ($i = 0;)
2) it sees a while statement (while ($i < 10)) and looks for a conditional statement
in the parenthesis (some condition) . It now checks whether the condition is
true. In our case the condition is whether $i is smaller than 10.
3) Since $i in the beginning is smaller than 10 it proceeds with executing what’s inside
the curly bracket {}.
4) It displays the message as instructed.
5) It increments $i, which means that 1 gets added to the value of $i. $i++; is the
same as $i = $i + 1;
6) It now goes back to the while statement/step 2
7) Steps 2 – 6 are repeated as long as the condition is true. When it's false, the loop
won’t be executed anymore.
FOR-Loops
We can rewrite the above example like this.
<?php
for ($i = 0; $i < 10; $i++)
{
echo "$i Hello World!<br>";
}
?>
The output of this loop will look exactly the same as in the while loop. But we have saved
ourselves two lines of code.
The for-loop is the same as the while loop except that we have packed the initialisation of $i,
the condition and the incrementing into on line.
The example on www.ucl.ac.uk/efrei/laqua/session2/loops.php includes a while and a for
loop. The output looks the same.
Introduction to Web Applications – IT Session 2
Arrays
An array is a variable that allows us to store a sequence of values. Each element in this
sequence can hold a single value only.
So for example, if we have a list of products, instead
pizza pasta salad of declaring a separate variable for each, we can
store them all in array and do useful things like
Figure 1 - a simple array of products looping over them for a drop down menu.
Figure 1 for example could be an array or products.
Associative Arrays
We can also create arrays that use strings (or other data types) as keys with values
associated with them (similar to a Hashmap). For example, if we wanted to store the product
name (key) and its price (value), we could do it like that:
$prices = array ( "pizza"=>3.99, "pasta"=>2.99, "salad"=>2.50 );
Again we can also initialise array elements one by one like this:
$prices [ "pizza" ] = 3.99;
$prices [ "pasta" ] = 2.99;
$prices [ "salad" ] = 2.50;
In order to access the elements in the array we use the key like this:
$prices [ "pizza" ];
$prices [ "pasta" ];
$prices [ "salad" ];
Using Loops with Associative Arrays
Because associative arrays are not numerically indexed we have to use a slightly different
strategy in order to access them with loops. Here are the two main strategies:
Introduction to Web Applications – IT Session 2
Foreach
foreach ($prices as $key => $value)
{
echo $key." => ".$value."<br>";
}
While Loop with Each Construct
We can also use the following construct:
while ( $element = each ( $prices ) )
{
echo $element [ "key" ];
echo " : ";
echo $element [ "value" ];
echo "<br>";
}
In this while loop we use the each () function. This function returns the current element of the
$prices array in a new array ($element) and makes the next element the current one. Thus in
the while loop the each () function returns every element and stops when the end of the array
is reached. In this code the variable $element is an associative array that gets reinitialised
every time the loops goes through one round.
A more elegant way of looping through an associative array is using the list () function.
Here's an example:
list ( $product, $price ) = each ($prices);
That way we separate the two elements and we can display them individually like this:
while (list ( $product, $price ) = each ($prices))
{
echo "$product - $price <br>";
}
Please note:
The each () function keeps track of the current element when looping through the array. So if
we want to use the array twice in the same page, we need to reset the current element back
to the start of the array using the reset () function like this:
reset ($prices)
while (list ( $product, $price ) = each ($prices))
{
echo "$product - $price <br>";
}
Exercises
Exercise 1 – Using Loops
Loops can make it easier for us to repetitively code things like table rows (<tr></tr>) or
drop down menus.
So let's make a little web form that lets the user select his date of birth from a drop down
menu. In normal HTML we'd have to write one line of code for each year of birth. With PHP
we can simply use a loop. Here's the example:
http://www.ucl.ac.uk/efrei/laqua/session2/exercise1.php
This is what a normal HTML drop down menu looks like with all the options hard coded inside.
<h3>Please select your year of birth:
</h3>
<form action="" method="get">
<select name="YOB">
<option>Year of Birth</option>
<option value=1930>1930</option>
<option value=1931>1931</option>
<option value=1932>1932</option>
// ... everything up to 1995??? That's a lot of code!
</select>
</form>
Introduction to Web Applications – IT Session 2
If we want to have the options 1930 – 1995, that would be pretty long.
What you need to do:
- initialise a variable at 1930 and …
- use a for-loop to loops through each option until 1995
Here's the draft code:
http://www.ucl.ac.uk/efrei/laqua/session2/exercise1DraftCode.txt
Challenge
If all of the above is too easy for you try this:
Take the order form you created last time but add text fields which allow you to enter the
customer name, product name and price and it calculates the total and displays your name.
Here's an example:
http://www.ucl.ac.uk/efrei/bonhard/Session-6/orderFORM.php
Hint:
- you'll have to use the predefined $HTTP_GET_VARS or $HTTP_POST_VARS variable.
This let's you pass variables from one page to another. For more info on that check
the PHP manual on www.php.net or check out this tutorial
http://www.pscode.com/vb/scripts/ShowCode.asp?txtCodeId=500&lngWId=8
- you'll also need to use a form which submits the data to itself. Here's a tutorial for
using forms http://www.htmlgoodies.com/tutors/forms.html . Please note, instead of
ACTION="mailto:" you should use the name of your PHP page i.e.
ACTION="myPage.php". That way you submit the data to this page.
- you'll need to use IF statements for creating an error messages, i.e.
if ($myVariable)
{
// do something if $myVariable is initialized/has a value
}
- add colours and proper formatting to make the page look pretty!