What We Will Cover
Elucidations
Homework Questions?
^ top
13.1: Arrays in PHP
Learner Outcomes
At the end of the lesson the student will be able to:
Create an array
Populate and reference values from an array
Work with array items
^ top
13.1.1: Introduction to Arrays
Previously we discussed how PHP handles single-valued data types
Now we discuss how PHP handles list of data known as arrays
Recall that an array is a collection of data values organized using a single name
Each data value has an index to distinguishes it from other values in the array
The easiest type of index to work with is a whole number, or integer
Each data value (element) of an array is identified by its name and index like this:
arrayName [index ]
For example, we might have an array of the names of the days of the week like the following:
Element
Value
$dayName[0]
"Sunday"
$dayName[1]
"Monday"
$dayName[2]
"Tuesday"
$dayName[3]
"Wednesday"
$dayName[4]
"Thursday"
$dayName[5]
"Friday"
$dayName[6]
"Saturday"
Why Do We Need Arrays?
An array is like a little database holding information
Once the array is populated with the data, extracting the data is easy
A variable name and an index like: $dayName[1]
You could use individual variables for all the data
However, this get cumbersome quite quickly
Imagine keeping track of test scores for an exam
Keeping scores for 5 students in 5 different variables is OK, but what about 100 or 1000 students?
How would you name all the variables?
How would you add the scores up for all the students?
Anytime you have more than two or three variables of the same thing, it is usually better to store the data in an array
We will see later in this lesson how we can process array data using loops
Using a loop, you can do more with arrays than you can with individual variables
Also, we will see that PHP uses arrays in many ways such as in form processing
^ top
13.1.2: Creating and Populating an Array
Like other PHP variables, arrays do not need to be declared in advance
Just type the variable name followed by square brackets
You can assign a value to a single array element:
$myArray[] = "someValue";
After assignment, you can use array element like any other variable:
print $myArray[0];
By default, arrays indexes start at zero (0 )< For example:
<?php
// Initializing values
$myArray [] = "zero" ;
$myArray [] = "one" ;
$myArray [] = "two" ;
// Accessing values
echo "$myArray[0], $myArray[1], $myArray[2]" ;
?>
Produces the output:
zero, one, two
Using the array() Function
You can use the array() function to initialize arrays as well
For example:
<?php
// Initializing values
$myArray = array( "zero" , "one" , "two" );
// Accessing values
echo "$myArray[0], $myArray[1], $myArray[2]" ;
?>
Produces the output:
zero, one, two
^ top
13.1.3: Working with Array Items
Individual array elements are accessed using the array name and an index
You use the array operator [] to specify the index
Arrays indexes can be literal values or a variable:
For example:
<?php
$dayName = array( "Sunday" , "Monday" , "Tuesday" ,
"Wednesday" , "Thursday" , "Friday" , "Saturday" );
$myIndex = 6 ;
echo "$dayName[0]<br />$dayName[1]<br />" ;
echo $dayName [ 2 ]. "<br />$dayName[3]<br />" ;
echo "$dayName[4]<br />$dayName[5]<br />" ;
echo $dayName [ $myIndex ];
?>
Produces the output:
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
If you wish, you can set start an index with a number other than 0
With the following, we set the first index to the number 1
The special notation => is used to specify a key value in the array function like:
array(1=>"Sunday", ... );
Values added to an array without specifying an index use the previously assigned maximum integer index plus one (+1)
For instance:
<?php
$dayName = array( 1 => "Sunday" , "Monday" , "Tuesday" ,
"Wednesday" , "Thursday" , "Friday" , "Saturday" );
echo "$dayName[1]<br />$dayName[2]<br />
$dayName[3]<br />$dayName[4]<br />
$dayName[5]<br />$dayName[6]<br />" ;
echo $dayName [ 7 ];
?>
Produces the output:
Sunday Monday
Tuesday Wednesday
Thursday Friday Saturday
Note that if you try to use an index that does not have a value, PHP returns NULL
NULL is a special value meaning, "no value assigned"
^ top
13.1.4: Working with Array Functions
PHP has many functions that let you interact with and manipulate arrays in various ways
For a complete list see the PHP documentation: Array Functions
We will look at a few of the more commonly used functions here
Working with Array Length
PHP arrays can change size as you use them, unlike some other languages
Also, you do not need to define a value for every item
Sparse arrays : arrays with several missing or null items
To determine the number of items in an array, you can use the count() function:
$numItems = count($arrayName );
For example:
<?php
$dayName = array( "Sunday" , "Monday" , "Tuesday" ,
"Wednesday" , "Thursday" , "Friday" , "Saturday" );
$numItems = count ( $dayName );
echo "count = $numItems" ;
?>
Produces the output:
count = 7
Another function that performs the same action as count() is sizeof()
Some Functions to Extract and Insert Array Items
Method
Description
array_push()
Adds one or more elements to the end of an array
array_pop()
Removes and returns the last element of an array
array_unshift()
Adds one or more elements to the beginning of an array
array_shift()
Removes the first element from an array
array_slice()
Extracts items from the middle of an array
array_splice()
General purpose method to insert items into or extract items from an array
^ top
13.1.5: Associative Arrays
Arrays indices in PHP can be strings rather than numbers
Arrays with non-integer indexes are known as associative arrays
Sometimes people refer to them as "hash tables " because they are often implemented using hash coding
Associative arrays are often used as a lookup table or cross reference between names and values
Creating Associative Arrays
You create an associative array like a regular array except you use strings for the index
For instance:
$course['CIS-132'] = 'Hodges';
$course['CIS-165PH'] = 'Parrish';
$course['DM-173B'] = 'Hodges';
You can create associative arrays with the array function as well
However, you must specify both the index and the value separated by =>
For instance, we can create a cross-reference between month names and number of days in the month:
$daysInMonth = array('Jan'=>31, 'Feb'=>28,
'Mar'=>31, 'Apr'=>30, 'May'=>31, 'Jun'=>30,
'Jul'=>31, 'Aug'=>31, 'Sep'=>30, 'Oct'=>31,
'Nov'=>30, 'Dec'=>31);
Then we can access an array element like this:
$daysInNov = $daysInMonth["Nov"];
Note that you can change the value of any array item by assigning a new value:
$course['CIS-132'] = 'Parrish';
Example Lookup Table for Days in Months
<?php
$daysInMonth = array( 'Jan' => 31 , 'Feb' => 28 ,
'Mar' => 31 , 'Apr' => 30 , 'May' => 31 , 'Jun' => 30 ,
'Jul' => 31 , 'Aug' => 31 , 'Sep' => 30 , 'Oct' => 31 ,
'Nov' => 30 , 'Dec' => 31 );
$daysInNov = $daysInMonth [ "Nov" ];
echo "Days in November: $daysInNov" ;
?>
Produces the output:
Days in November: 30
^ top
13.1.6: Summary
In this section, we looked at how to work with arrays
An array is a collection of data values organized using a single name
Arrays are convenient ways to process a list of data
Like other PHP variables, arrays do not need to be declared in advance
Just type the variable name followed by square brackets
You can assign a value to a single array element:
$myArray[] = "someValue";
After assignment, you can use array element like any other variable:
print $myArray[0];
An array function uses more compact code to initialize arrays:
$myArray = array("zero", "one", "two");
You can declare arrays in a form for processing in your PHP scripts
Place square brackets '[]' after the element's name
Array indexes in PHP can be strings rather than numbers
Allows cross-referencing, among other uses:
$months = array('Jan'=>31, 'Feb'=>28, 'Mar'=>31,
'Apr'=>30, 'May'=>31, 'Jun'=>30, 'Jul'=>31,
'Aug'=>31, 'Sep'=>30, 'Oct'=>31, 'Nov'=>30,
'Dec'=>31);
Check Yourself
What is an array?
What are the two ways you can declare and initialize an array?
What statement would you use to create an array named $dayNames?
What statements would you use to create an array named $dayNames and initialize it with the abbreviations for the days of the week, starting with "Sun" and going through "Sat"?
What expression would you use to return the third value from the array $dayNames?
^ top
Activity 13.1
Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.
Quick Quiz
^ top
13.2: Forms and PHP
Learner Outcomes
At the end of the lesson the student will be able to:
Pass data from HTML forms to PHP scripts
Use PHP functions to examine the form data
Save data in PHP variables for processing
Acquire data from multiple-valued form elements
^ top
13.2.1: Coding Forms for PHP
Input Elements
Input Types
Other Form Elements
^ top
13.2.2: Acquiring Form Data in PHP Scripts
PHP makes it easy to receive input data from forms
For instance, given the following input element:
<input type="text" name="fname">
We use $_REQUEST with square brackets and the element name like this:
$firstName = $_REQUEST["fname"];
print "firstName: $firstName";
If you only want to accept data passed using the GET method, use $_GET instead:
$firstName = $_GET["fname"];
print "firstName: $firstName";
If you only want to accept data passed using the POST method, use $_POST instead:
$firstName = $_POST["fname"];
print "firstName: $firstName";
These arrays are known as "autoglobals" or "superglobals" because they are automatically global throughout your PHP page
Superglobal Arrays Used with Forms
Array
Description
$_GET
Access to variables passed via the HTTP GET method.
$_POST
Access to variables passed via the HTTP POST method.
$_REQUEST
Access to variables passed via both the HTTP GET and POST methods.
^ top
13.2.3: Examining Form Data
Let us look at an example of form processing using PHP
In the form below we include the important attributes for PHP:
action: specifies the URL where the form sends the data for processing
method: specifies how to send the information
name: specifies the name for each form element
value: specifies the value for some types of form elements
Following form is the script for reading the form data
To read the data, the script uses the $_REQUEST array
To help debug forms and other data, PHP provides two functions you can use:
print_r() : prints a compact form of data about a variable
var_dump() : prints detailed information about a variable
The script displays the $_REQUEST array using both print_r() and var_dump()
The data from the functions is displayed inside of preformatted text elements
The pre-tags make the data more readable in a Web page
Following these functions are data extracted into single variables
Also, the script displays the variables
You can view the form here: Simple Input Form
Example Form for PHP Processing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Simple Input Form</title>
</head>
<body onload='document.forms[0].elements[0].focus();'>
<h2>Simple Input Form</h2>
<form method="get" action="formecho.php">
<table border="0" cellspacing="0" cellpadding="5">
<tr>
<td>First Name:</td>
<td><input type="text" name="fname" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="lname" /></td>
</tr>
<tr>
<td class="label">Shipping Option:</td>
<td>
<input type="radio" name="state" id="s1" value="CA" />
<label for="s1">California</label><br />
<input type="radio" name="state" id="s2" value="OR" />
<label for="s2">Oregon</label><br />
<input type="radio" name="state" id="s3" value="WA" />
<label for="s3">Washington</label>
</td>
</tr>
<tr>
<td class="label"> </td>
<td>
<input type="submit" name="submit" value="Continue">
</td>
</tr>
</table>
</form>
</body>
</html>
Example Script Reading the Form Data
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Form Echo</title>
</head>
<body>
<h2>Form Echo</h2>
<h3>Data Using <code>print_r()</code></h3>
<pre><?php print_r ( $_REQUEST ); ?> </pre>
<h3>Data Using <code>var_dump()</code></h3>
<pre><?php var_dump ( $_REQUEST ); ?> </pre>
<h3>Data into Single Variables</h3>
<?php
$firstName = $_REQUEST [ "fname" ];
$lastName = $_REQUEST [ "lname" ];
$state = $_REQUEST [ "state" ];
$submit = $_REQUEST [ "submit" ];
print "firstName: $firstName<br />" ;
print "lastName: $lastName<br />" ;
print "state: $state<br />" ;
print "submit: $submit" ;
?>
</pre>
</body>
</html>
^ top
13.2.4: Working with Selection Lists
Recall that a selection list is a list box from which a user selects a value or values
The syntax for the select and option elements is:
<select id="id" name="name">
<option value="value1">Item1</option>
<option value="value2">Item2</option>
...
</select>
For example, to code a selection list that returns a single value:
<select id="state" name="state">
<option value="CA">California</option>
<option value="OR" selected="selected">Oregon</option>
<option value="WA">Washington</option>
</select>
Which produces the output:
California
Oregon
Washington
A selection list that selects a single option is read like an input element by PHP
for instance, to read the option form the above selection list:
$state = $_REQUEST["state"];
print "state: $state";
Reading Multiple Values
Selection lists can return more than one value by including the multiple attribute
For example:
<select id="state2" name="state" multiple>
<option value="CA">California</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
</select>
Which produces the output:
California
Oregon
Washington
To select multiple values, you hold down the Ctrl key while selecting with the mouse
Normally, PHP only reads a single value from the potentially multiple selections
To read multiple values, you need to use square brackets after the name of the select list
For the above example:
<select id="state" name="state[] " multiple>
This tells PHP to store the multiple values in an array
You can see this in the following example
Also, you can view the form here: Form with Select List
Note that we need some way to process a variable number of items in the array
We will discuss how to do this using loops later in the lesson
Form with Select List for PHP Processing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Form with Select List</title>
</head>
<body onload='document.forms[0].elements[0].focus();'>
<h2>Form with Select List</h2>
<form method="get" action="formecho.php">
<table border="0" cellspacing="0" cellpadding="5">
<tr>
<td>First Name:</td>
<td><input type="text" name="fname" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="lname" /></td>
</tr>
<tr>
<td class="label">State:</td>
<td>
<select name="state[]" multiple>
<option value="CA">California</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
</select>
</td>
</tr>
<tr>
<td class="label"> </td>
<td>
<input type="submit" name="submit" value="Continue">
</td>
</tr>
</table>
</form>
</body>
</html>
^ top
13.2.5: Summary
In this section we looked at how you can use forms with PHP
Each form control element must have a name assigned to be read by PHP
PHP can read the form data using the superglobal array $_REQUEST, $_POST or $_GET
For instance, given the following input element:
<input type="text" name="fname">
We use $_REQUEST with square brackets and the element name like this:
$firstName = $_REQUEST["fname"];
print "firstName: $firstName";
You can view the data passed from a form using either:
print_r() : prints a compact form of data about a variable
var_dump() : prints detailed information about a variable
For example:
print_r($_REQUEST);
Some form elements, like selection lists, can return multiple values
To let PHP know that the form element can have multiple values, you must put square brackets after the name
For example:
<select name="state[] " multiple>
Check Yourself
What attribute must a form control element contain to be read by PHP?
What PHP code can you use to read a form element named "lname"?
What PHP functions can you use to view all the values of a form?
When a form control element can return multiple values, what special symbols must you include after the name?
^ top
Activity 13.2
Take one minute to read over the Review Questions in the textbook. We will discuss the questions as time permits.
^ top
13.3: Relationships, Truth and Conditions
Learner Outcomes
At the end of the lesson the student will be able to:
Use conditional statements to compare numerical and string data values
Use conditional statements to test form values
^ top
13.3.1: Relationship Values and Truth
In addition to arithmetical operations, all computers can compare numbers
Many decisions can be reduced to choosing between two numbers
Comparing numbers can make computers seem "intelligent"
Expressions that compare two numbers are called relational expressions
Simple relational expressions have one relational operator comparing two values:
A relational expression always evaluates to either true or false
You can see the relational operators in the following table
Note that operators === and !== include the type of the data when making the comparison
Relational Operators
Math
Name
PHP
Example
Result
=
Equal to
== or ===
5 == 10 2 == 2
false true
≠
Not equal to
!= or !==
5 != 10 2 != 2
true false
<
Less than
<
5 < 10 5 < 5 5 < 2
true false false
≤
Less than or equal to
<=
5 <= 10 5 <= 5 5 <= 2
true true false
>
Greater than
>
5 > 10 5 > 5 5 > 2
false false true
≥
Greater than or equal to
>=
5 >= 10 5 >= 5 5 >= 2
false true true
What is Truth?
"What is truth?" may seem more appropriate for philosophy than programming
However, in programming we have to know how the computer interprets truth
PHP interprets the following as false and every other value as true:
boolean FALSE
integer 0 (zero)
float 0.0 (zero)
empty strings "", and the string "0"
arrays with zero elements (not covered yet)
objects with zero elements (not covered yet)
special type NULL (such as variables not assigned a value)
Note that a NULL character (\0) does not display anything in a browser
To view information about variables, you can use var_dump()
Thus, to see the truth of a relational expression, you can use something like:
var_dump(5 == 10);
More Information
^ top
13.3.2: Using the if-else Statement
The if-else statement lets us choose between two alternatives based on a condition
A condition is some state upon which the execution of some statements depends
The condition must evaluate to either true or false
If a condition evaluates to true
Otherwise it is false
The syntax of the if-else statement:
if (condition) {
statements1;
} else {
statements2;
}
As an example, we can code an if-else statement like this:
if ($_REQUEST["guess"] == 7) {
print "<p>*** Correct! ***</p>\n";
} else {
print "<p>Sorry, that is not correct.</p>\n";
}
For clarity, if and else are written on different lines than the nested statements
Also, the nested statements are indented
For an example using an if-else statement, we will write a simple guessing game application
We collect a guess from the player with the simple form shown below
We then evaluate the form with the test script
You can play the game yourself by clicking: Guessing Game
Form Collecting the Players Guess
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Guessing Game</title>
</head>
<body onload='document.forms[0].elements[0].focus();'>
<h2>Guessing Game</h2>
<p>I'm thinking of a number between 1 and 10.<p>
<p>Can you guess it?</p>
<form action="guesstest.php" method="get">
<input type="text" name="guess"><br /><br />
<input type="submit" name="submit" value="Check Guess">
<input type="reset" value="Reset">
</form>
</body>
</html>
Script Testing the Form Data
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Guessing Game Response</title>
</head>
<body>
<?php
if ( $_REQUEST [ "guess" ] == 7 ) {
print "<p>*** Correct! ***</p>\n" ;
print '<a href="guessform.html">Play again</a>' ;
} else {
print "<p>Sorry, that is not correct.</p>\n" ;
print '<a href="guessform.html">Guess again</a>' ;
}
?>
</body>
</html>
Omitting the else Clause
More Information
if : the PHP Manual
else : the PHP Manual
^ top
13.3.3: Using the elseif Statement
For Example
More Information
^ top
13.3.4: Working with Logical Operators
Sometimes you want to consider several relational expressions at once
For this we can use logical operators
Use ! (NOT) operator to reverse value of expression
Use and to AND two or more conditions
Also, you can spell AND as: &&
Use or to OR two or more conditions
Also, you can spell OR as: ||
and operator returns true only if expressions on both sides are true
or operator returns true if either expression is true
You can see examples of these conditions in the following tables
! Operator
If expr is...
Then ! expr is...
Example
Result
true
false
!true
false
false
true
!(5 < 2)
true
and (&& ) Operator
If expr1 is...
And expr2 is...
Then expr1 and expr2 is...
Example
Result
true
true
true
5 < 10 and 5 > 2
true
true
false
false
5 < 10 and 5 < 2
false
false
true
false
5 > 10 and 5 > 2
false
false
false
false
5 > 10 and 5 < 2
false
or (|| ) Operator
If expr1 is...
|| expr2 is...
Then expr1 or expr2 is...
Example
Result
true
true
true
5 < 10 or 5 > 2
true
true
false
true
5 < 10 or 5 < 2
true
false
true
true
5 > 10 or 5 > 2
true
false
false
false
5 > 10 or 5 < 2
false
Testing a Range of Values
Check Yourself
More Information
^ top
13.3.5: Comparing Strings
PHP stores string values using the ASCII code
Acronym for American Standard Code for Information Interchange
Pronounced ("ask-ee")
ASCII provides a standard, numerical way to represent characters
Every letter, number, and symbol is translated into a code number
Digits are stored in order from '0' to '9':
Digit '0 ' is code value 48
Digit '1 ' is code value 49
And so on to '9 ', which is code value 57
Uppercase letters of the alphabet are stored in order from 'A' to 'Z':
Letter 'A ' is code value 65
Letter 'B ' is code value 66
Up to 'Z ' which is code value 90
Similarly, lowercase letters are stored in order from 'a' to 'z':
Letter 'a ' is code value 97
Letter 'b ' is code value 98
Up to 'z ' which is code value 122
Also, a space is code value 32, which is less than all letters and digits
Comparing Codes
Notice that digits come before uppercase letters
Also, uppercase letters come before lowercase letters
Since all letters and digits are numbers, you can compare strings just like numbers
PHP lets you use all the relational operators to compare string values:
==, !=, <, >, <= and >=
These operators produce results like you would expect when comparing words alphabetically
The following example shows the results of comparing two words
You can try the form by clicking: String Input
Form Collecting the Strings for Comparison
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>String Input</title>
</head>
<body onload='document.forms[0].elements[0].focus();'>
<h2>String Input</h2>
<p>Enter two strings and I will compare them.<p>
<form action="stringcompare.php" method="get">
<table border="0" cellspacing="0" cellpadding="6">
<tr><td>
<label for="s1">First string:</label>
</td>
<td>
<input type="text" name="s1" id="s1">
</td></tr>
<tr><td>
<label for="s2">Second string:</label>
</td>
<td>
<input type="text" name="s2" id="s2">
</td></tr>
<tr><td> </td>
<td>
<input type="submit" name="submit" value="Compare">
<input type="reset" value="Reset">
</td></tr>
</table>
</form>
</body>
</html>
Script Comparing the Strings
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>String Comparison</title>
</head>
<body>
<?php
$s1 = $_REQUEST [ "s1" ];
$s2 = $_REQUEST [ "s2" ];
if ( $s1 == $s2 ) {
print "<p>The strings are equal</p>\n" ;
} elseif ( $s1 < $s2 ) {
print "<p>'$s1' is less than '$s2'</p>\n" ;
} else {
print "<p>'$s1' is greated than '$s2'</p>\n" ;
}
?>
</body>
</html>
More Information
^ top
13.3.6: Summary
Many decisions can be reduced to choosing between two numbers
Comparing numbers can make computers seem "intelligent"
To compare numbers, you use relational operators
PHP relational operators include:
== === != !== < <= > >= <= >=
Similarly, you can compare letters since letters are stored as numbers
Relational expressions always evaluate to either true or false
To make choices in your scripts, use one of the following statements:
if
if-else
if elseif elseif ... else
When you need to compare several conditions, you use logical operators:
! and or
For example:
if (($num < 1) or ($num > 10) {
print "Error: enter a number between 1 and 10";
}
Check Yourself
Which PHP values evaluate to false and which evaluate to true?
Why can you compare character data using a relational expression?
When does an and (&&) of two or more conditions evaluate to true?
When does an or (||) of two or more conditions evaluate to false?
What is the effect of the NOT (!) operator?
^ top
Activity 13.3
Take one minute to review the Check Yourself questions. We will discuss the questions as time permits.
^ top
13.4: Using Loops to Repeat Statements
Learner Outcomes
At the end of the lesson the student will be able to:
Work with for loops
Work with while loops
Loop through the contents of an array
^ top
13.4.1: About Programming Loops
Sometimes we want to repeat certain statements in PHP
For example, consider the code to produce a selection list:
<select id="weekday" name="weekday"> <option value="Sunday">Sunday</option> <option value="Monday">Monday</option> <option value="Tuesday">Tuesday</option> <option value="Wednesday">Wednesday</option> <option value="Thursday">Thursday</option> <option value="Friday">Friday</option> <option value="Saturday">Saturday</option> </select>
Which produces the form control:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Note that this code contains a lot of repeated text
It may not seem so bad for only seven items, but it can become cumbersome with 50, 100 or more items
Programmers deal with this type of situation using loops
A loop is a set of statements that are executed repeatedly
PHP has 3 general-purpose looping statements:
while
do-while
for
We will start with the while loop statement
^ top
13.4.2: Using the while and do-while Loops
Diagram of while Loop Operation
Using the while Loop
You can use a while loop to count by adding a counter variable
For example:
<?php
//Initialization
$count = 0 ;
echo "Before loop: count = $count" ;
while ( $count < 5 ) { //loop condition
//loop body
$count = $count + 1 ;
echo "<br>count = $count\n" ;
}
echo "<br>After loop: count = $count" ;
?>
Produces the output:
Before loop: count = 0 count = 1
count = 2
count = 3
count = 4
count = 5
After loop: count = 5
About the do-while Loop
More Information
^ top
13.4.3: Using the for Loop
Execution Sequence
When the for loop is reached, execute the initialization statement
Check if condition is true
if true then continue with Step 3
Otherwise, continue with Step 6
Execute the statements inside the curly braces
When end of loop body is reached, execute the iteration statement
Return to Step 2
Loop is finished: continue with statements after the loop
Example Using the for Loop
Check Yourself
Lets check our understanding of the for loop with the following code
Write down what you think the program will display before you check the answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Testing the PHP for Loop</title>
</head>
<body>
<?php
print "First loop:<br />";
for ($count = 0; $count < 5; $count++) {
print "$count<br />";
}
print "Second loop:<br />";
for ($count = 5; $count > 0; $count--) {
print "$count<br />";
}
print "Third loop:<br />";
for ($i = 0; $i <= 360; $i += 60) {
print "$i<br />";
}
print "Fourth loop:<br />";
for ($i = 1; $i <= 64; $i *= 2) {
print "$i<br />";
}
?>
</body>
</html>
Check answer
About those Curly Braces
Technically, the a loop statement affects only the single statement that follows
We use curly braces to make that one statement into a block of statements
This allows us to put any number of statements within the block
Curly braces are not always required, but the best practice is to always include them
More Information
^ top
13.4.4: Using Arrays and Loops to Create Selection Lists
Displaying a Selection List
Using this structure, let us use arrays and loops to create a selection list
First we create an array containing the data we want to display:
$dayName = array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
Then we loop through the values of the array and print each array value in an option tag:
for ($i = 0; $i < count($dayName); $i++) {
print "<option value=\"$dayName[$i]\">";
print "$dayName[$i]</option>\n";
}
Finally, we place the PHP code between the opening and closing select tags
You can see the complete code for this in the following example
Code Creating a Selection List
<select id="weekday1" name="weekday"><?php $dayName = array( "Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" ); for ( $i = 0 ; $i < count ( $dayName ); $i ++) { print "<option value=\"$dayName[$i]\">" ; print "$dayName[$i]</option>\n" ; } ?> </select>
^ top
13.4.5: Using the foreach Loop
Example Using foreach
Lets revisit our selection list example using the foreach loop
<select id="weekday2" name="weekday"><?php $dayName = array( "Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" ); foreach ( $dayName as $day ) { print "<option value=\"$day\">" ; print "$day</option>\n" ; } ?> </select>
Produces the output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Notice how the loop code is simplified by removing the counting variable
More Information
^ top
13.4.6: Summary
Loops are used to repeat sections of code
The while loop is the simplest loop statement with the syntax:
while (condition ) {
statements to repeat
}
A variation on the while loop is the do-while loop:
do {
statements to repeat
} while (condition );
By checking the condition at the end of the loop, the statements to repeat are guaranteed to execute at least one time
A more compact repetition statement is the for loop:
for (initialization ; condition ; iteration ) {
statements to repeat
}
Loops are often used as a way to iterate through array items
PHP has a special type of loop for use with arrays named foreach
The syntax of the foreach loop is:
foreach ($arrayName as $item ) {
statements to repeat
}
For each iteration of the array, the loop assigns the next value in the list to $item
Check Yourself
What is a loop?
What is the purpose of a loop test condition?
What is the code for a for statement that uses a counter variable named counter that starts with the value 0 and continues up to and including 100 in increments of 10?
What loop statement would you code to create a selection list with the values and option text set to the items in an array?
^ top
Activity 13.4
Take one minute to review the Check Yourself questions. We will discuss the questions as time permits.
^ top
Wrap Up
Due Next: Final Project Report and Presentation (12/11/06)
^ top
Home
| WebCT
| Announcements
| Schedule
| Room Policies
| Course Info
Help
| FAQ's
| HowTo's
| Links
Last Updated: November 27 2006 @20:12:53