0% found this document useful (0 votes)
76 views

Session-2-Loops & Arrays

This document introduces control structures and arrays in PHP. It discusses conditionals like IF/ELSE statements that allow controlling program flow based on conditions. It also covers repetition structures like WHILE and FOR loops that execute code repeatedly. Finally, it explains arrays, which allow storing multiple values in a variable. Arrays can be numerically indexed or associative (using non-numeric keys) and values can be accessed using loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views

Session-2-Loops & Arrays

This document introduces control structures and arrays in PHP. It discusses conditionals like IF/ELSE statements that allow controlling program flow based on conditions. It also covers repetition structures like WHILE and FOR loops that execute code repeatedly. Finally, it explains arrays, which allow storing multiple values in a variable. Arrays can be numerically indexed or associative (using non-numeric keys) and values can be accessed using loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Introduction to Web Applications – IT Session 2

IT Session 2 – Control Structures & Arrays


Control Structures & Arrays
Control structures allow us to control the flow of execution of a program or script. The broad
groups are conditionals (IF/ELSE) and repetition structures (Loops).
Arrays are a variable type that allows us to store multiple data items/sequence of values.
Since you've done some C++ programming this will be extremely easy for you …

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.

Numerically Indexed Arrays


In order to access the elements of an array we need some form of indexing them. As the
name suggests numerically indexed arrays use numbers in order to determine the position of
a value. These are arrays like those in most other programming languages like C, C++ or
Java. Here's how you initialise it in PHP:
$products = array ('pizza', 'pasta', 'salad') ;
You can also initialise the array bit by bit like:
$products [0] = "pizza";
$products [1] = "pasta";
$products [2] = "salad";
In effect an array does not have to have a fixed length, but can be of variable length. In order
to access/change its contents you use the following command:
$products [0] = "icecream"; -this will change the "pizza"(item at pos. 0) to
"icecream"
To display the contents, you have to do this:
echo "$products[0] $products[1] $products[2]";

See an example here: http://www.ucl.ac.uk/efrei/laqua/session2/arrays.php and see


http://www.ucl.ac.uk/efrei/laqua/session2/arraysCode.txt for the PHP Code.
Using Loops to Access Arrays
Because the arrays are indexed by numbers, we can access the contents with loops. For
example:
for ($i=0; $i<3; $i++)
{
echo "products [$i]<br>";
}

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

Exercise 2 – Using arrays and loops


Now let's imagine we're using an array to store the names of our products and their prices
and we'd like to display them in a table, one row for each product & price. Here's what it
should look like:
http://www.ucl.ac.uk/efrei/laqua/session2/exercise2.php
What you need to do:
- initialise an associative array that contains your product names and prices
- insert this code into the HTML and make loop over the array using the list () function
to generate the rows of products. You can find the outline of the code here:
Here's the draft code you can use:
http://www.ucl.ac.uk/efrei/laqua/session2/exercise2DraftCode.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!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy