What We Will Cover
Elucidations
Homework Questions?
Quiz Questions?
- Comments on using the suggested organization for your project?
^ top
8.1: 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
|
^ top
8.1.1: Flow of Control
- As in most programming language, PHP handles flow of control with branching and looping statements
- PHP branching and looping statements are the same as C, C++ and Java and very similar to other languages
- Most branching and looping statements are controlled by a test condition
- The test condition evaluates to either
true or false
Relational Expressions
- The simplest test conditions are comparison of two values such as:
$count <= 5
- These comparisons always have one relational operator comparing two values

- The operators are known as comparison operators or relational operators
- The following tables shows the PHP relational operators you can use to compare two expressions
Table of 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 |
Comparing Strings
- Note that comparison operators work with strings as well as numbers
- With strings, comparison is performed in alphabetical order using ASCII:
- Digits before letters
- Uppercase letters come before lowercase letters
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 the boolean value
false is displayed by PHP as the NULL character ('\0')
- However, the
NULL character ('\0') does not display anything in a browser
- To view information about boolean values, you can use
var_dump()
- Thus, to see the truth of a relational expression, you can use something like:
var_dump(5 == 10);
- The following example shows several relational operators in action
- To view the example, click here
Example Displaying Several Comparisons
<html>
<head><title>PHP Script</title></head>
<body>
<pre>
<?php
$count = 5;
echo "$count == 5: ";
var_dump($count == 5);
echo "$count != 5: ";
var_dump($count != 5);
echo "$count < 10: ";
var_dump($count < 10);
echo "$count <= 10: ";
var_dump($count <= 10);
echo "$count > 10: ";
var_dump($count > 10);
echo "$count >= 10: ";
var_dump($count >= 10);
?>
</pre>
</body>
</html>
More Information
^ top
8.1.2: Using the if-else Statement
- An
if-else statement chooses between two alternatives based on a single test condition
- For example, if we are writing a simple guessing game and want to comment on a users guess:
if ($guess == 7) {
echo "<p>*** Correct! ***</p>\n";
} else {
echo "<p>Sorry, that is not correct.</p>\n";
}
- General syntax:
if (test) {
// execute statements only if true
} else {
// execute statements only if false
}
- The test condition is in the parenthesis and evaluates to a Boolean value of
true or false
- The statements to execute are usually enclosed in curly braces
- If the curly braces are left off then the if and else only applies to the next statement
- Notice that there is no test condition for the
else clause
- For clarity, the
if and else are written on different lines than the nested statements
- Also, the statements are indented
Conditional Example
- In this example we create a simple guessing game application
- We use a simple form to collect a guess from the user
- Save the following as guessform.html in the
htdocs/phptest directory of your localhost Web server
<html>
<head>
<title>Guessing Game!</title>
</head>
<body>
<form method="get" action="guess.php">
<p>I'm thinking of a number between 1 and 10.<p>
<p>Can you guess it?</p>
<input type="text" name="guess" size="20"></p>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
- We report the success on the following page, where the form sends its data
- Save the following as
guess.php in the same directory as guessform.html
<html>
<head>
<title>Guessing Game Response</title>
</head>
<body>
<?php
$guess = $_REQUEST["guess"];
if ($guess == 7) {
echo "<p>*** Correct! ***</p>\n";
} else {
echo "<p>Sorry, that is not correct.</p>\n";
}
?>
</body>
</html>
Omitting the else
- Sometimes you want one alternative to do nothing at all
- In PHP, you can accomplish this by omitting the
else clause
More Information
^ top
8.1.3: Nested Conditional Statements
- We can have several statements in either the
if or else clause
- One of these nested statements can be another
if or if-else statement
Multiple Alternatives
- By using collections of
if-else statements, a program can distinguish between multiple alternatives
- For example, we can rewrite our guessing game to provide hints on the guess:
$guess = $_REQUEST["guess"];
if ($guess == 7) {
echo "<p>*** Correct! ***</p>\n";
} else if ($guess < 7) {
echo "<p>Sorry, that is too low.</p>\n";
} else {
echo "<p>Sorry, that is too high.</p>\n";
}
- By nesting an if statement in an else clause we are able to choose from multiple alternatives
- The test conditions are evaluated in order until one of the tests evaluates to
true
- At that point the statements in that part of the structure are executed and then the rest of the
if-else-if is skipped
- The final
else clause is optional and serves as a default in case all the other conditions are not met
Using elseif
More Information
^ top
8.1.4: Using Logical Operators
- Sometimes you want to consider several test conditions 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
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 |
! Operator
| If expr is... |
Then ! expr is... |
Example |
Result |
true |
false |
!true |
false |
false |
true |
!(5 < 2) |
true |
Logical Example
Check Yourself
More Information
^ top
Exercise 8.1
In this exercise we explore using relational and logical operators with if-else statements. As an example, we will calculate a student's letter grade according to the following table:
| Numerical Grade |
Letter Grade |
| greater than or equal to 90 |
A |
| less than 90 but greater than or equal to 80 |
B |
| less than 80 but greater than or equal to 70 |
C |
| less than 70 but greater than or equal to 60 |
D |
| less than 60 |
F |
Specifications
- Open the XAMPP Control Panel by double-clicking the icon on the desktop or by using the Apache Friends entry in the start menu.

- Start the Apache and MySQL modules, if they are not already running.

- Start TextPad, or another text editor, and enter this starter code:
<html>
<head>
<title>Score Entry Form</title>
</head>
<body>
<h1>Find Your Grade</h1>
<form method="get" action="grade.php">
<p>What was your score?
<input type="text" name="score" size="10"></p>
<input type=submit name="submit">
</form>
</body>
</html>
- Save this code in a file named
grade.html to the htdocs directory and phptest subdirectory of your Apache (XAMPP) installation (htdocs/phptest).
If you installed XAMPP on Windows using the default settings, the htdocs directory is C:\xampp\htdocs. Also, the Start menu has an entry that opens the htdocs directory by following Start -> Apache Friends -> XAMPP -> XAMPP httpdoc folder. On other systems you will need to search for the htdocs directory. If the subdirectory phptest is missing, then you will need to create a new one.
- Open a new Web browser tab or window and enter
localhost/phptest/grade.html in the address field.
You should see a page like the following in the browser:
- Copy the following PHP script into a text editor and save the file in your
phptest directory as grade.php:
<html>
<head><title>Grade Report</title></head>
<body>
<?php
$score = trim($_REQUEST["score"]);
print "The score was $score, which is an ";
// Enter code here
?>
</body>
</html>
This is the file in which you will be making changes.
- Add conditional statements to the
grade.php file that uses the $score variable to determine the grade based on the score. For example, your first statement might be:
if ($score >= 90) {
echo "A";
}
- Once you have completed writing the statements, test your code with several scores to make sure it works correctly.
- Submit your final
grade.php file (the one you made the changes to) to Blackboard as part of assignment 8.
As time permits, be prepared to answer the Check Yourself questions in the section: 8.1.5: Summary.
^ top
8.1.5: Summary
- As in most programming language, PHP handles flow of control with branching and looping statements
- PHP branching and looping statements are the same as C, C++ and Java and very similar to other languages
- Most branching and looping statements are controlled by a test condition
- The test condition evaluates to either
true or false
- he simplest test conditions use relational operators
- 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:
if
if else
if elseif elseif ... else
- We can have several statements in either the
if or else clause
- One of these nested statements can be another
if or if-else statement
- By using collections of
if-else statements, a program can distinguish between multiple alternatives, like:
$guess = $_REQUEST["guess"];
if ($guess == 7) {
echo "<p>*** Correct! ***</p>\n";
} else if ($guess < 7) {
echo "<p>Sorry, that is too low.</p>\n";
} else {
echo "<p>Sorry, that is too high.</p>\n";
}
- As a shortcut for the else-if part, PHP provides
elseif
- For example, rewriting the previous example to use
elseif:
$guess = $_REQUEST["guess"];
if ($guess == 7) {
echo "<p>*** Correct! ***</p>\n";
} elseif ($guess < 7) {
echo "<p>Sorry, that is too low.</p>\n";
} else {
echo "<p>Sorry, that is too high.</p>\n";
}
- When you need to compare several conditions, you can use logical operators
! and or
- For example:
if (($num < 1) or ($num > 10)) {
print "Error: enter a number between 1 and 10";
}
Quick Quiz
Check Yourself
- What is meant by the term "flow of control"? (8.1.1)
- What is a relational expression and why are they used? (8.1.1)
- What are the two possible values to which a relational expression evaluates? (8.1.1)
- In PHP, what values evaluate to true? (8.1.1)
- True of false? PHP can compare both numbers and strings with relational expressions. (8.1.3)
- What is an
if-else statement used for? (8.1.2)
- Does the syntax for an
else clause include a test condition? (8.1.2)
- True of false? The order of
if and if-else statements never matters. (8.1.2)
- True of false? An elegant way to choose among multiple alternatives is to nest
if statements in an else clause. (8.1.3)
- When does an AND (
&&) of two or more conditions evaluate to true? (8.1.4)
- When does an OR (
||) of two or more conditions evaluate to false? (8.1.4)
- What is the effect of the NOT (
!) operator? (8.1.4)
^ top
8.2: Using Loops to Repeat statements
Learner Outcomes
At the end of the lesson the student will be able to:
- Use
while and for statements to repeat sections of code
- Apply commonly-used looping patterns
- Avoid common looping problems
|
^ top
8.2.1: Introduction to Loops
- Looping statements in PHP are the same as C, C++ and Java and very similar to other languages
- PHP has three general-purpose looping statements:
while
do-while
for
- In addition, PHP has a special purpose
foreach looping statement we will cover later
- The code that repeats in a loop is called the body of the loop
- Each repetition of a loop is called an iteration
^ top
8.2.2: Using the for Loop
- When
for statement reached -- initialization executes
- If the test condition evaluates to
true:
- Execute statements in the body of the loop
- When the end of loop body is reached, execute the update statement
- Return to step 2
- Otherwise, the loop is finished so continue with statements after the loop
More Information
^ top
8.2.3: Using the while and do-while Loop
The do-while Loop
More Information
^ top
8.2.4: Nesting Loops
- We can have several statements in a loop
- One of these nested statements can be another loop
- When nesting, it is important to use indentation to show the nesting of the loops
- The following example shows several loop examples
- We use the loops to print the rows and columns of an HTML table
- The first loop prints the table heading
- Following this is a nested loop
- The outer loop iterates through each row of the nested loop
- The nested inner loop prints each column of the table
- To see the loop click here
Example of Nested Loop
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
|
<html>
<head><title>Loopy Table</title></head>
<body>
<h1>Loopy Table</h1>
<table border="1" style="text-align:right;">
<?php
$start = 1;
$maxCol = $start + 9;
$maxRow = $start + 9;
echo "<tr>\n";
echo "<th>x</th>\n";
// Print the heading
for ($col = 1; $col < $maxCol; $col++) {
echo "<th> $col</th>\n";
}
echo "</tr>\n";
// Outer loop to iterate through each row
for ($row = 1; $row < $maxRow; $row++) {
echo "<tr>\n";
echo "<td><b>$row</b></td>\n";
// Inner loop prints each column
for ($col = 1; $col < $maxCol; $col++) {
$value = $row * $col;
echo "<td>$value</td>\n";
}
echo "</tr>\n";
}
?>
</table>
</body>
</html>
|
Increment and Decrement Operators
- Notice the
++ operator in the previous example
$row++
- The the
++ operator is an arithmetic shortcut called the increment operator
- The increment operator (
++) adds 1 to a variable's value
- A similar operator is the decrement operator (
--) which subtracts 1 from a variable's value
^ top
Exercise 8.2
In this exercise we explore how to use loops in PHP.
Specifications
- Copy the following PHP script into a text editor, save the file in your
phptest directory as loopy.php, and then view the file as a Web page in your browser.
<?php
$max = 5;
for ($i = 0; $i < $max; $i = $i + 1) {
echo "i = $i <br>";
}
echo "After loop i = $i" ;
?>
The page should display the numbers from 0 to 4.
- Change the code in
loopy.php to use a while loop rather than a for loop.
Both for loops and while loops can perform the same tasks.
- Submit your final
loopy.php file to Blackboard as part of assignment 8.
As time permits, be prepared to answer the Check Yourself questions in the section: 8.2.5: Summary.
^ top
8.2.5: Summary
Quick Quiz
Check Yourself
- What are PHP's three general purpose looping statements? (8.2.1)
- What are the four things to consider when working with loops? (8.2.2)
- What part of a loop is repeated? (8.2.2)
- What is the purpose of a loop test condition? (8.2.2)
- What is the purpose of the loop initialization code? (8.2.2)
- 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? (8.2.2)
- What is the syntax of a
while statement? (8.2.3)
- True of false? A use for a nested loop is to print the rows and columns of a table. (8.2.4)
^ top
8.3: Using Arrays
Learner Outcomes
At the end of the lesson the student will be able to:
- Write code to initialize arrays
- Access array elements
|
- Sometimes useful to group related data values into a list
- Can use a variable type called an array to store data in a list
- Then able to operate on the array data as a group
^ top
8.3.1: About Arrays
Array: a list of data values where each individual value is access by an index
- Arrays are a type of data structure -- a way to organize data
- An array is used to process a collection of data as a group like
- Why do we need arrays?
- Imagine keeping track of 5 test scores, or 100, or 1000 in a program
- How would you name all the variables?
- How would you process each of the variables?
- Arrays provide a convenient solution to these problems
- Entire array referred to by a single identifier
- Each element uniquely identified by an index
Example Array
- One-dimensional array is like single row of data in spreadsheet or table
$score[0] |
$score[1] |
$score[2] |
$score[3] |
$score[4] |
| 90 |
95 |
87 |
89 |
98 |
- Top row shows the indices for an array named "
$score"
- Individual items are referenced by the index inside the square brackets
[ ]
- By default, array indexes start at the number 0
- PHP uses a type of array known as an associative array, or "ordered map"
- This means that indexes can be strings as well as numbers
- In the exercise we will explore how to create and use arrays in PHP
^ top
8.3.2: Creating and Populating Arrays
- Like other PHP variables, arrays do not need to be declared in advance
- For example, to create an array named
numbers with three elements:
$numbers[0] = "zero";
$numbers[1] = "one";
$numbers[2] = "two";
- After assignment, you can use array element like any other variable
echo "$numbers[0], $numbers[1], $numbers[2]";
- By default, arrays indexes start at zero (
0)
- Thus you can skip the numbers in the square brackets like this:
$numbers[] = "zero";
$numbers[] = "one";
$numbers[] = "two";
- If you do not assign your own index, PHP automatically assigns the next highest index starting a 0
- The following examples assigns three values one after another without specifying an index:
<?php
// Creating an array
$numbers[] = "zero";
$numbers[] = "one";
$numbers[] = "two";
// Accessing values
echo "$numbers[0], $numbers[1], $numbers[2]";
?>
Using the Array Function
- Another way to create arrays is with the
array() function.
- By default, the
array() function numbers array indexes starting at 0
- For example:
<?php
// Creating an array
$numbers = array("zero", "one", "two");
// Accessing values
echo "$numbers[0], $numbers[1], $numbers[2]";
?>
^ top
8.3.3: Selecting Array Items
- Individual array elements are accessed using the array name and an index
- Use the array operator
[] to specify the index
- Indexes should be an integer expression or a string
- Arrays indexes can be literal values or a variable
<?php
$weekDay = array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
echo "$weekDay[0]<br>$weekDay[1]<br>";
echo "$weekDay[2]<br>$weekDay[3]<br>";
echo "$weekDay[4]<br>$weekDay[5]<br>";
echo $weekDay[6];
?>
- If you wish, you can set one or more index values for your array
<?php
$weekDay = array(1=>"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
echo "$weekDay[1]<br>$weekDay[2]<br>";
echo "$weekDay[3]<br>$weekDay[4]<br>";
echo "$weekDay[5]<br>$weekDay[6]<br>";
echo $weekDay[7];
?>
- Above example sets the first index to the number
1
- Subsequent assignment of values use the maximum index
+ 1
- If you try to access an index beyond those defined, PHP returns
NULL
^ top
8.3.4: Using Loops with Arrays
- Loops are often used as a way to iterate (
) through array items
- For example, the following code uses a loop to list each item in an array
- Uses the count function to return the number of items in the array
<?php
$weekDay = array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
for ($i = 0; $i < count($weekDay); $i++) {
echo "$weekDay[$i]<br>";
}
?>
- Note the use of
$i++ as a shortcut for adding one to a variable
- The statement:
$i++;
is equivalent to:
$i = $i + 1;
- Similarly, the statement:
$i--;
is equivalent to:
$i = $i - 1;
Using foreach
Example Using foreach
- The following code displays the contents of the array named
$dayName
<?php
$weekDay = array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
foreach ($weekDay as $day) {
echo "$day<br>";
}
?>
- Note that each array item is accessed and displayed in order
^ top
8.3.5: Associative Arrays
- Arrays indices in PHP can be strings rather than numbers
- Known as an associative array or ordered maps
- The string value is used to look up the location of the data value
- You can use such an array as a cross reference between names and values
Creating Associative Arrays
- The following code creates an associative array
$course['cis154'] = 'Parrish';
$course['cis156'] = 'Griffith';
$course['cis165'] = 'Parrish';
- Also, you can create associative arrays with the
array function
- You must specify the index name followed by
=> and the value
- For instance, we can create a cross-reference between month names and number of days in the month
$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);
- Then we can access an array element like this:
$days = $months['Nov'];
- This is similar syntax to arrays we have used so far
- The main difference is the use of string values within the square brackets
- When used with the
foreach statement, you can access both the index name and item name
foreach ($months as $name=>$days) {
print "Index = $name and value = $days<br>";
}
- Also, you can change the value of any array item by assigning it a new value
$course['cis156'] = 'Griffin';
Example of an Array with String indexes
<?php
$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);
foreach ($months as $name=>$days) {
print "Index = $name and value = $days<br>";
}
?>
^ top
8.3.6: Functions for Working With Arrays
- Like the PHP mathematical functions we looked at in lesson 6.2.7, PHP has functions that work with arrays
- Some functions, like
print_r() and var_dump() work not only with arrays but other variable types as well
Using print_r() and var_dump()
- Functions
print_r() and var_dump() display information about a variable
- You use these functions for debugging when you want to understand the state of a variable
- For example:
<?php
$weekDay = array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
echo "<pre>";
print_r($weekDay);
var_dump($weekDay);
echo "</pre>";
?>
- The
pre tags show the formatting of the function output
Using count() and sizeof()
- If you want to know how may elements are in an array, you can use either
count() or sizeof()
- For example:
<?php
$weekDay = array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
echo "The count of elements in the array is ";
echo count($weekDay);
echo "<br>The size of the array is ";
echo sizeof($weekDay);
?>
- Function
sizeof() is an alias for count()
Using isset() and unset()
- Sometimes you want to remove an element from an array
- In this case you can use the
unset() function like this:
<?php
$weekDay = array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
if (isset($weekDay[1])) {
echo "Blue Monday<br>\n";
} else {
echo "No Monday<br>\n";
}
echo "Removing Monday's<br>\n";
unset($weekDay[1]); // Goodbye Monday
if (isset($weekDay[1])) {
echo "Blue Monday<br>\n";
} else {
echo "No Monday<br>\n";
}
?>
- Notice that function
isset() is testing for the presence of the array element
More Information
^ top
Exercise 8.3
In this exercise we explore how to use arrays in PHP.
Specifications
- Copy the following PHP script into a text editor, save the file in your
phptest directory as arrays.php, and then view the file as a Web page in your browser.
<html>
<head><title>PHP Script</title></head>
<body>
<?php
// Enter your PHP code here
?>
</body>
</html>
- We will first look at how to create an array in PHP. Copy the following code between the PHP tags and then save and reload (refresh) the page:
$numbers[0] = "zero";
$numbers[1] = "one";
$numbers[2] = "two";
echo "$numbers[0], $numbers[1], $numbers[2]";
You should see the words, "zero, one, two", displayed on the page. Like other PHP variables, you do not need to declare arrays before assigning them values. For more information see section 8.3.2: Creating and Populating Arrays.
- By default, PHP numbers array indexes starting at 0. Replace the previous code with the following, where the numbers have been removed from the square brackets in the assignment statements:
$numbers[] = "zero";
$numbers[] = "one";
$numbers[] = "two";
echo "$numbers[0], $numbers[1], $numbers[2]";
When assigning a value, PHP will automatically increment the indexes, starting from 0, if we do not assign our own index values. For more information see section 8.3.2: Creating and Populating Arrays.
- Another way to create arrays is with the
array() function. Replace the previous code with the following:
$numbers = array("zero", "one", "two");
echo "$numbers[0], $numbers[1], $numbers[2]";
By default, the array() function numbers array indexes starting at 0. For more information see section 8.3.2: Creating and Populating Arrays.
- If we want to start array numbering somewhere other than 0 while using the array() function, we can specify the starting location using an arrow (
=>) before the first item. To see this, replace the previous code with the following:
$numbers = array(1=>"zero", "one", "two");
echo "$numbers[1], $numbers[2], $numbers[3]";
Notice how we access each array element after it is created using square brackets. For more information see section 8.3.3: Selecting Array Items.
- Since array indexes are numbers, we can access each element with an index variable and a counting loop. Replace the previous code with the following:
$colors = array("red", "green", "yellow", "orange");
for ($i = 0; $i < 4; $i++) {
echo "$colors[$i]<br>\n";
}
The index variable $i is used to control the counting loop. For more information see section 8.3.4: Using Loops with Arrays.
- Using a loop to access every element of an array is very common. Because of this PHP has a special loop called the foreach loop. Replace the previous code with the following:
$colors = array("red", "green", "yellow", "orange");
foreach ($colors as $item) {
echo "$item<br>\n";
}
The foreach loop access each array item in order. For more information see section 8.3.4: Using Loops with Arrays.
- Arrays indices in PHP can be strings rather than numbers. To use arrays with strings, we need to map the key (index) to the value as shown below. To see the associative array in action, replace the previous code with the following:
$colors = array("apple"=>"red", "kiwi"=>"green");
$colors["banana"] = "yellow";
$colors["orange"] = "orange";
foreach ($colors as $fruit=>$color) {
echo "$fruit color is $color<br>\n";
}
Notice that the array function uses the arrow (=>) to map the key to the value (key=>value). You can map keys to values using square brackets and the assignment operator as well. For more information see section 8.3.5: Associative Arrays.
- If you want to see every element of an array for debugging, you do not need to use a loop. PHP provides two functions for this:
print_r() and var_dump(). You can see how they work by adding after the foreach loop:
echo "<pre>";
print_r($colors);
var_dump($colors);
echo "</pre>";
The pre tags show the formatting of the function output. For more information on these and other functions see section 8.3.6: Functions for Working With Arrays.
- Submit your final
arrays.php file to Blackboard as part of assignment 8.
As time permits, be prepared to answer the Check Yourself questions in the section: 8.3.7: Summary.
^ top
8.3.7: Summary
- 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
echo $myArray[0];
- An array function uses more compact code to initialize arrays
$myArray = array("zero", "one", "two");
- Loops are often used as a way to iterate through array items
- PHP has a special type of loop for use with arrays: foreach
- You can declare arrays in a form for processing in you PHP scripts
- Place square brackets '
[]' after the element name
- Arrays indices 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);
- You can use
print_r() and var_dump() to view information about an array
var_dump($months);
Quick Quiz
Check Yourself
- What is an array? (8.3.1)
- Why do we use arrays? (8.3.1)
- What is an array index? (8.3.1)
- What are two ways you can create and initialize an array? (8.3.2)
- What statement would you use to create an array named
$colors? (8.3.2)
- 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"? (8.3.2)
- What expression would you use to return the third value from the array
dayNames? (8.3.3)
- How do you display an array using a loop? (8.3.4)
- True of false? You can use string values as the index of an array. (8.3.5)
- What is a good way to display information about an array for debugging purposes? (8.3.6)
- If you want to know how many elements are in an array, what function can you use? (8.3.6)
- If you want to remove an element from an array, what function can you use? (8.3.6)
^ top
8.4: Arrays, Forms and Meta-data
Learner Outcomes
At the end of the lesson the student will be able to:
- Fetch data from MySQL in arrays
- Create HTML tables
- Display MySQL data in HTML tables
- Use result set metadata
|
^ top
8.4.1: Using Arrays for Multiple Form Values
Example Checkboxes with the Same Name
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>Languages</title></head>
<body>
<h3>Make your vote</h3>
<form action="langscript.php" method="post">
<p>Preferences:
<?php
$prefs = array("ASP","JSP","PHP","Other");
foreach ($prefs as $item) {
print '<input type="checkbox" name="pref[]" value="';
print $item.'"> '.$item;
}
?>
<p><input type="submit" value="Click to Vote!"></p>
</form>
</body>
</html>
Example Script Processing Form Data with Multiple Values
<html>
<head>
<title>Your Vote Counts!</title>
</head>
<body>
<h3>Your Vote Counts!</h3>
<?php
if (empty($_REQUEST['pref'])) {
print "Oh no! Please vote!";
} else {
print "<p>You voted for: <ul>";
foreach ($_REQUEST['pref'] as $item) {
print("<li>$item</li>");
}
print "</ul>";
}
?>
</body>
</html>
Notes on the Code
More Information
^ top
8.4.2: Fetching Data from MySQL in Arrays
Checking the Result Set
Example Using mysql_fetch_assoc()
- Let us create a PHP script by copying the following code into a text editor
- Save the file as
datafetch.php in the htdocs/phptest directory of your localhost Web server
<? require_once("includes/dbconvars.php");
// Open the connection $dbCnx = mysql_connect($dbhost, $dbuser, $dbpwd) or die("Could not connect: ".mysql_error()); mysql_select_db($dbname, $dbCnx) or die("Could not select db: ".mysql_error());
// Make the query $sql = "SELECT * FROM products"; $result = mysql_query($sql) or die("Query failed: ".mysql_error());
// Count number of rows returned $numRows = mysql_num_rows($result); echo "<p>Number of rows: $numRows</p>\n";
// Outer loop copies each row into $row while ($row = mysql_fetch_assoc($result)) { // Inner loop displays each column of $row echo "<p>"; foreach ($row as $item) { echo "$item "; } echo "</p>\n"; }
// Clean up mysql_free_result($result); mysql_close($dbCnx); ?>
Notes on the Code
- Note that the outer loop copies each row of data into
$row
$row is an array, which means we can iterate through all the columns using a loop
- As long as
mysql_fetch_assoc() returns a row, the test condition of the loop evaluates to true
- The inner loop displays each column of data using a foreach loop
- What do you think of the layout of the data?
More Information
^ top
8.4.3: Displaying MySQL Data in Tables
- You can use HTML tables to neatly format MySQL data
- Using our previous example, we add table tags in the correct locations
For Example
<? require_once("includes/dbconvars.php");
// Open the connection $dbCnx = mysql_connect($dbhost, $dbuser, $dbpwd) or die("Could not connect: ".mysql_error()); mysql_select_db($dbname, $dbCnx) or die("Could not select db: ".mysql_error());
// Make the query $sql = "SELECT * FROM products"; $result = mysql_query($sql) or die("Query failed: ".mysql_error());
// Count number of rows returned $numRows = mysql_num_rows($result); print "<p>Number of rows: $numRows</p>\n";
// Show the results in a table print "<table border=\"1\">\n"; while ($row = mysql_fetch_assoc($result)) { echo "<tr>\n"; foreach ($row as $item) { echo "<td> $item</td>\n"; } echo "</tr>\n"; } print "</table>\n";
// Clean up mysql_free_result($result); mysql_close($dbCnx); ?>
^ top
8.4.4: Adding Column Names with Meta-data
for ($i = 0; $i < $count; $i++) {
print "<th>".mysql_field_name($result, $i)."</th>\n";
}
<? require_once("includes/dbconvars.php");
// Open the connection $dbCnx = mysql_connect($dbhost, $dbuser, $dbpwd) or die("Could not connect: ".mysql_error()); mysql_select_db($dbname, $dbCnx) or die("Could not select db: ".mysql_error());
// Make the query $sql = "SELECT * FROM products"; $result = mysql_query($sql, $dbCnx) or die("Query failed: ".mysql_error());
// Show the table name echo "<h4>Table: "; echo mysql_field_table($result, 0); echo "</h4>\n";
echo "<table border>\n"; // Show the column names as table headings echo "<tr>\n"; $count = mysql_num_fields($result); for ($i = 0; $i < $count; $i++) { echo "<th> "; echo mysql_field_name($result, $i); echo "</th>\n"; } echo "</tr>\n";
// Show the result set data using HTML tables while ($row = mysql_fetch_assoc($result)) { echo "<tr>\n"; foreach ($row as $item) { echo "<td> $item</td>\n"; } echo "</tr>\n"; } echo "</table>\n";
// Clean up mysql_free_result($result); mysql_close($dbCnx); ?>
More Information
^ top
Exercise 8.4
In this exercise we explore how to use arrays with MySQL. For this exercise you will need the Artzy database installed, which we completed in Exercise 2.1.
Specifications
- Verify your computer has the following connection information in a file named
dbconvars.php in a subdirectory named includes of the phptest directory:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpwd = "";
$dbname = "artzy";
?>
If needed, change the values assigned to $dbuser and $dbpwd to match your MySQL installation. In the classroom, $dbuser = root; and $dbpwd = password;. For more information see lesson 6.3.1: Connecting to a MySQL Database.
- Copy the following PHP script into a text editor, save the file in your
phptest directory as prodselect.php, and then view the file as a Web page in your browser.
<html>
<head><title>Product Selection</title></head>
<body>
<h1>Product Selection</h1>
<form action="prodreport.php" method="GET" name="cust">
<p>Select a Product:
<?php
// Enter your PHP code here
?>
</p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
Notice that we have declared a form to which we will add a selection list using data from the Artzy database.
- Inside the PHP tags, add the PHP statements to connect to the Artzy database:
require_once("includes/dbconvars.php");
// Open the connection
$dbCnx = mysql_connect($dbhost, $dbuser, $dbpwd)
or die("Could not connect: ".mysql_error());
mysql_select_db($dbname, $dbCnx)
or die("Could not select db: ".mysql_error());
For more information see lesson 6.3.1: Connecting to a MySQL Database.
- There are two parts to an option tag, the value and words to display. We want to retrieve both parts from our database. Add the following code after all the other PHP statements:
// Make the query
$sql = "SELECT ID, ProductName FROM products";
$result = mysql_query($sql)
or die("Query failed: ".mysql_error());
For more information on selection lists see lesson 7.2.4: Other Form Elements.
- From the result set returned by the query, we want to build a selection list. Add the following code after all the other PHP statements:

Notice that we are using one of the PHP functions that extract data from a result set into an array. For more information see section 8.4.2: Fetching Data from MySQL in Arrays.
- Finally, add the code to free the result set memory and close the MySQL connection after all the other PHP statements:
// Clean up
mysql_free_result($result);
mysql_close($dbCnx);
For more information see lesson 6.3.3: Cleaning Up.
- Reload (refresh) the Web page and verify you see the following form:
Verify the selection list displays the six products from the Artzy database. If you do not see the correct results then compare your source code against the listing at the end of this exercise. Also, view the source and notice the value and content displayed in the selection list.
- To create the report page, copy the following PHP script into a text editor, and save the file in your
phptest directory as prodreport.php
<html>
<head><title>Product Report</title></head>
<body>
<h1>Product Report</h1>
<?php
var_dump($_REQUEST); // replace this statement
?>
</body>
</html>
- Select a product on your
prodselect.php page and press the submit button. Verify that you see a page like the following:
The exact "prodselect" value will depend on which product you selected. If your do not see the report then check your work and correct the problem before continuing. If you cannot correct the problem after a reasonable time, then ask the instructor for help.
- Replace the
var_dump() function call with the following statement to retrieve the value of "prodselect" submitted by the form:
$id = $_REQUEST["prodselect"];
For more information see lesson 7.2.5: Processing Form Data with PHP.
- Inside the PHP tags, add the PHP statements to connect to the Artzy database after the previous PHP code:
require_once("includes/dbconvars.php");
// Open the connection
$dbCnx = mysql_connect($dbhost, $dbuser, $dbpwd)
or die("Could not connect: ".mysql_error());
mysql_select_db($dbname, $dbCnx)
or die("Could not select db: ".mysql_error());
For more information see lesson 6.3.1: Connecting to a MySQL Database.
- Since we know the ID of the selected product, we can tailor our query to retrieve only the one product. Add the following code after all the other PHP statements:
// Make the query
$sql = "SELECT ProductName AS 'Product Name',
ProductDescription As 'Product Description',
Price, InStock AS Quantity
FROM products WHERE ID = $id";
$result = mysql_query($sql)
or die("Query failed: ".mysql_error());
Notice that we are using two column aliases in our SELECT statement. For more information see lesson 2.3.4: Using an Alias.
- From the result set returned by the query, we want to build a table from the data. Add the following code after all the other PHP statements:

Notice that we are using meta data from the result set to display the column names. For more information see section 8.4.4: Adding Column Names with Meta-data.
- Finally, add the code to free the result set memory and close the MySQL connection after all the other PHP statements:
// Clean up
mysql_free_result($result);
mysql_close($dbCnx);
For more information see lesson 6.3.3: Cleaning Up.
- Reload (refresh) the
prodreport.php page and verify you see a table of data displayed. If you do not see the table, then verify your work including reentering the form data. If you do not see the correct results then compare your source code against the listing at the end of this exercise.
- Submit both your final
prodselect.php and prodreport.php files to Blackboard as part of assignment 8.
Check Yourself
As time permits, be prepared to answer these questions. You can find more information by following the links after the question.
- True of false? Checkboxes and selection lists can submit multiple values to a form processing script. (8.4.1)
- What PHP functions can you use to extract and entire row of data from a result set? (8.4.2)
- In what format is the extracted returned from these functions? (8.4.2)
- What is meta-data? (8.4.4)
Listing of prodselect.php

Listing of prodreport.php

^ top
8.4.5: Summary
- In this section we looked at PHP functions for extracting data from a result set into an array
- Using this technique, an entire row of data is returned from the result set
- Each column (field) of the row is contained in the elements of the array
- In addition, we looked at using HTML tables to format the retrieved data
- We also found that we could use the meta data functions to label the columns of our table
Quick Quiz
^ top
Wrap Up
Due Next: A8-Query and Report (4/20/09) Quiz 8 and Discussion Chapter 9 (4/20/09)
When class is over, please shut down your computer if it is on
^ top
Home
| WebCT
| Announcements
| Course info
| Expectations
| Schedule
Project
| Help
| FAQ's
| HowTo's
| Links
Last Updated: May 21 2009 @12:09:10
|