# 8. Control-Flow and Arrays

## 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

### 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++, Java and most other programming languages
• Most branching and looping statements are controlled by a test condition
• The test condition evaluates to either `true` or `false`

#### Relational Expressions

• Many test conditions are comparisons between 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 we can use to compare two expressions

#### Table of Relational Operators

 Math Name PHP Example Result = Equal to `==` or `===` `5 == 102 == 2` falsetrue ≠ Not equal to `!=` or `!==` `5 != 102 != 2` truefalse < Less than `<` `5 < 105 < 55 < 2` truefalsefalse ≤ Less than or equal to `<=` `5 <= 105 <= 55 <= 2` truetruefalse > Greater than `>` `5 > 105 > 55 > 2` falsefalsetrue ≥ Greater than or equal to `>=` `5 >= 105 >= 55 >= 2` falsetruetrue

#### Comparing Strings

• Note that comparison operators work with strings as well as numbers
• With strings, comparison is performed in alphabetical order using ASCII:
1. Digits before letters
2. Uppercase letters 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 true and false
• 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, we can use `var_dump()`
• Thus, to see the truth of a relational expression, we can use something like:
`var_dump(5 == 10);`
• The following example shows several relational operators in action

#### Example Displaying Several Comparisons

```<html>
<body>
<pre>
<?php
\$count = 5;
echo "\$count == 5: ";
var_dump(\$count == 5);
echo "\$count != 5: ";
var_dump(\$count != 5);
echo "\$count &lt; 10: ";
var_dump(\$count < 10);
echo "\$count &lt;= 10: ";
var_dump(\$count <= 10);
echo "\$count &gt; 10: ";
var_dump(\$count > 10);
echo "\$count &gt;= 10: ";
var_dump(\$count >= 10);
?>
</pre>
</body>
</html>
```

#### Check Yourself

1. True or false: a test condition always evaluates to either `true` or `false`.
2. Of the following, ________ is not a valid relational expression in PHP.
```\$x = 0;
\$y = 1;
```
1. `\$x = \$y`
2. `\$x !== \$y`
3. `\$x < "7"`
4. `\$x > 42`
3. Strings are compared in ________ order.

### 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 our localhost Web server
```<html>
<title>Guessing Game!</title>

<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 we want to execute statements only when a certain condition is true
• We do not want an alternative to execute if the test condition is false
• In PHP, we can accomplish this by omitting the `else` clause

#### Check Yourself

1. The problem with the following if-else statement is that ________.
```if (7 == \$guess) {
echo "*** Correct! ***";
} else (7 != \$guess) {
echo = "Sorry, that is not correct.";
}
```
2. The value of `x` after the following code segment executes is ________.
```int \$x = 5;
if (\$x > 3) {
\$x = \$x - 2;
} else {
\$x = \$x + 2;
}
```
3. To execute statements only when a certain condition is true, use an ______ statement without the else clause.

### 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`

• Since an `if-else-if` structure is so commonly used, PHP has a shortcut version for the `else-if` part: `elseif`
• As the name suggests, `elseif` is a combination of an `else` followed by an `if`
• This variation saves a whopping one space in our source code for every `elseif` we use
• For example, rewriting our 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";
}
```

#### Check Yourself

1. True or false: you can nest `if` statements in the `if` clause, the `else` clause, or both.
2. True or false: for the following code, the statement `if (\$guess < 7)` is nested in the else clause of the first if-statement.
```\$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";
}
```
3. In the code above, the test condition of the first `if`-statement must be ________ before the second `if`-statement executes.
4. PHP lets you combine an else-if statement using the keyword ________.

### 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 `&&` to AND two or more conditions
• We can spell AND as: `and`
• However, `and` has lower precedence than `&&`
• Use `||` to OR two or more conditions
• We can spell OR as: `or`
• However, `or` has lower precedence than `||`
• `&&` operator returns `true` only if expressions on both sides are true
• `||` operator returns `true` if either expression is true
• Some people like to construct a truth table to verify the logic of a condition

#### `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`
• Remember that PHP allows `true` to be `1` and `false` to be `0`
• If we substitute `1` for `true` and `0` for `false`, we have these truth tables:

• With this substitution we see that the AND operation is the minimum of the inputs
• Conversely, the OR operation is the maximum of the inputs

#### Confusing `&&` and `||` Conditions

• Many people confuse `&&` and `||` conditions, especially when learning about logical operators
• A value lies between 0 and 100 if the value is at least 0 and at most 100
• A value is outside that range if it is less than 0 or greater than 100
• There is no golden rule; we have to think carefully and test our conditions

#### Check Yourself

1. Of the following groups ________ is larger.
1. Students wearing denim
2. Students wearing denim AND corrective lenses
2. Of the following groups ________ is larger.
1. Students wearing denim
2. Students wearing denim OR corrective lenses
3. Of the following groups ________ is larger.
1. Students wearing denim
2. Students wearing denim AND NOT corrective lenses
4. Of the following logical expressions, ________ tests to see if `\$x` is between 1 and 10 (including 1 and 10).
1. `(\$x >= 1 && \$x <= 10)`
2. `(1 <= \$x <= 10)`
3. `(\$x >= 1 or \$x <= 10)`
4. `(1 <= \$x || \$x <= 10)`
5. Trying to run the following code displays ________.
```if (\$bb or !\$bb) {
echo "That is the question!";
}
```
1. That is the question!
2. Nothing
3. PHP throws an error
4. It depends on the value of `\$bb`

### 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:

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

1. Open the XAMPP Control Panel by double-clicking the icon on the desktop or by using the Apache Friends entry in the start menu.

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

3. 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> ```

4. 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`. 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.

5. 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:

6. Copy the following PHP script into a text editor and save the file in your `phptest` directory as `grade.php`:
```<html>
<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.

7. 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";
}
```
8. Once you have completed writing the statements, test your code with several scores to make sure it works correctly.
9. Save your completed `grade.php` file (the one you made the changes to) to submit 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.

### 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++, Java and most other programming 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

1. If `a = 4` and `b = 5`, the expression `a > b` evaluates to .
2. You may nest ________ `else`-`if` statement(s) in a PHP program:

3. The `else` statement is the default conditional selected when all possible conditions are not met.

#### Check Yourself

1. What is meant by the term "flow of control"? (8.1.1)
2. What is a relational expression and why are they used? (8.1.1)
3. What are the two possible values to which a relational expression evaluates? (8.1.1)
4. In PHP, what values evaluate to true? (8.1.1)
5. True of false? PHP can compare both numbers and strings with relational expressions. (8.1.3)
6. What is an `if-else` statement used for? (8.1.2)
7. Does the syntax for an `else` clause include a test condition? (8.1.2)
8. True of false? The order of `if` and `if-else` statements never matters. (8.1.2)
9. True of false? An elegant way to choose among multiple alternatives is to nest `if` statements in an `else` clause. (8.1.3)
10. When does an AND (`&&`) of two or more conditions evaluate to `true`? (8.1.4)
11. When does an OR (`||`) of two or more conditions evaluate to `false`? (8.1.4)
12. What is the effect of the NOT (`!`) operator? (8.1.4)

## 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

### 8.2.1: Introduction to Loops

• Looping statements in PHP are the same as C, C++, Java and most other programming languages
• A loop is a block of code that can execute repeatedly
• Whether or not a program repeats a block of code is determined by a test condition
• The test condition is checked each time through the loop
• PHP has three general-purpose looping statements:
```for
while
do-while
```
• 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

#### Check Yourself

1. The purpose of a loop is to ________ a block of code.
2. True or false: a test condition is checked each time a loop repeats.
3. The three general purpose loops are: ________, ________ and ________.

### 8.2.2: Using the `for` Loop

• Whenever we work with a loop, we need to consider these things:
1. Loop body -- which statements to repeat
2. Test condition -- when to loop and when to stop
3. Test update -- what must change to exit the loop
4. Initialization code -- how to start the loop correctly
• The `for` loop provides a syntax for these things in a compact form:
```for (initialization; test; update) {
// statements to repeat
}
```
• Where:
• initialization: statement to execute before the loop starts
• test: condition to evaluate at the start of each iteration
• update: statement to execute at the end of the loop
• The statements to repeat are enclosed in curly brackets
• For example:
```<?php
\$max = 5;
for (\$i = 0; \$i < \$max; \$i = \$i + 1) {
echo "i = \$i <br>";
}
echo "After loop i = \$i" ;
?>
```

Try it!

• The `for` loop is primarily used for counting as shown in the example above
• The execution sequence of a `for` loop is:
1. When `for` statement reached -- initialization executes
2. If the test condition evaluates to `true`:
1. Execute statements in the body of the loop
2. When the end of loop body is reached, execute the update statement
3. Otherwise, the loop is finished so continue with statements after the loop

#### Increment and Decrement Operators

• Adding 1 to a number is very common in programming
• Because it is so common, the developers of PHP included a shortcut
• Instead of: `\$i = \$i + 1`
• We can write: `\$i++` or `++\$i`
• If we want to subtract 1 we can write: `\$i--` or `--\$i`
• These are known as the increment (`++`) and decrement (`--`) operators
• Using the increment operator, we could rewrite the for-loop like this:
```for (\$i = 0; \$i < \$max; \$i++)
{
echo "i = \$i <br>";
}
```

#### Check Yourself

1. The following statements will output ________.
```for (\$count = 0; \$count < 5; \$count++) {
print "\$count ";
}
```
1. 0 1 2 3 4
2. 0 1 2 3 4 5
3. 1 2 3 4
4. 5 4 3 2 1
2. The following statements will output ________.
```for (\$count = 5; \$count > 0; \$count--) {
print "\$count ";
}
```
1. 0 1 2 3 4
2. 5 4 3 2 1 0
3. 5 4 3
4. 5 4 3 2 1
3. For the above loop, enter the initialization statement.

4. For the same loop, enter the test condition.

5. For the same loop, enter the update statement.

### 8.2.3: Using the `while` and `do-while` Loop

• The simpler `while` loop has the following syntax:
```while (test) {
// statements to repeat
}
```
• Where test is the condition to evaluate at the start of each iteration
• For example:
```\$count = 0;
while (\$count < 5) {
echo "count = \$count<br>";
\$count = \$count + 1;
}
```
• Because of its simpler form, the `while` loop is considered a more general purpose loop
• However, we still have to include the four parts of a loop design:
1. Loop body -- which statements to repeat
2. Test condition -- when to loop and when to stop
3. Test update -- what must change to exit the loop
4. Initialization code -- how to start the loop correctly

#### The do-while Loop

• A variation on the `while` statement is the `do-while`, which tests the condition at the end of the loop body:
```do {
// statements to repeat
} while (test); //test condition
```
• Where test is the condition to evaluate at the end of each iteration
• For example:
```\$count = 0;
do {
echo "count = \$count<br>";
\$count = \$count + 1;
} while (\$count < 5);
```
• Testing at the end ensures a minimum of at least one iteration
• Thus we use the `do`-`while` loop when we want to ensure at least one iteration

#### Check Yourself

1. True or false: a `while`-loop includes an initialization statement as part of its syntax.
2. A test condition must evaluate to ________ for a `while` loop to execute its body of statements.
3. If the test condition of a `while`-loop evaluates to false, the statement after the ________ executes.
4. True or false: the test of a do-while loop occurs at the end of the loop.
5. True or false: the body of a do-while loop always executes at least one time.

### 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
• The first loop prints the table heading
```for (\$col = 1; \$col < \$maxCol; \$col++) {
echo "<th>&nbsp;&nbsp;&nbsp;\$col</th>\n";
}
```
• Following this is a nested loop to print the rows and columns of an HTML table
• The outer loop iterates through each row of the nested loop
• The nested inner loop prints each column of the table

#### 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 ``` ``` Loopy Table

Loopy Table

\n"; echo "
x   \$col
\$row\$value
\n"; // Print the heading for (\$col = 1; \$col < \$maxCol; \$col++) { echo "\n"; } echo "\n"; // Outer loop to iterate through each row for (\$row = 1; \$row < \$maxRow; \$row++) { echo "\n"; echo "\n"; // Inner loop prints each column for (\$col = 1; \$col < \$maxCol; \$col++) { \$value = \$row * \$col; echo "\n"; } echo "\n"; } ?> ```

#### Check Yourself

1. True or false: loops can be nested inside other loops.
2. To keep track of the rows and columns of a table, we need ________ loop statements.
3. True or false: an inner loop runs to completion every time an outer loop repeats one time.
4. In the following nested loop, the `echo` statement is called ________ times.
```for (\$x = 0; \$x < 5; \$x++) {
for (\$y = 0; \$y < 10; \$y++) {
echo "x=\$x, y=\$y<br>");
}
}
```

### Exercise 8.2

In this exercise we explore how to use loops in PHP.

#### Specifications

1. 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.

2. 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.

3. Save your final `loopy.php` file to submit 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.

### 8.2.5: Summary

• Loops are used to repeat sections of code
• Whenever we work with a loop, we need to consider these things:
1. Loop body -- which statements to repeat
2. Test condition -- when to loop and when to stop
3. Test update -- what must change to exit the loop
4. Initialization code -- how to start the loop correctly
• The `while` loop is the most basic repetition statement
• A more compact repetition statement is the `for` loop
```for (initialization; condition; update) {
//loop body
}
```
• It is legal code to have one loop nested inside another
• We looked at an example that built an HTML table

#### Quick Quiz

1. When using a while loop, the loop body will run for as long as a specific condition is met.

2. What will be output after the following statements have been executed?
```\$count;
for (\$count = 1; \$count < 4; \$count++) {
print (\$count + " ");
}
```

3. When working with a counting loop, you must always the counting variable.

#### Check Yourself

1. What are PHP's three general purpose looping statements? (8.2.1)
2. What are the four things to consider when working with loops? (8.2.2)
3. What part of a loop is repeated? (8.2.2)
4. What is the purpose of a loop test condition? (8.2.2)
5. What is the purpose of the loop initialization code? (8.2.2)
6. 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)
7. What is the syntax of a `while` statement? (8.2.3)
8. True of false? A use for a nested loop is to print the rows and columns of a table. (8.2.4)

## 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

• Oftentimes we need to process a list of data
• For example, we may want to work with the days of the week like:
1. Sunday
2. Monday
3. Tuesday
4. Wednesday
5. Thursday
6. Friday
7. Saturday
• One way to work with a list of data is to use an array

Array: an ordered collection of data values organized using a single name

• Arrays are a type of data structure -- a way to organize data
• The entire array is referred to by a single identifier
• Each item in the array is known as an element
• Each element is uniquely identified by an index

#### Example Array

• An array is a list of data
• For example, we might create an array to contain the days of the week like the following:

Element Value
`\$weekDay[0]` "Sunday"
`\$weekDay[1]` "Monday"
`\$weekDay[2]` "Tuesday"
`\$weekDay[3]` "Wednesday"
`\$weekDay[4]` "Thursday"
`\$weekDay[5]` "Friday"
`\$weekDay[6]` "Saturday"

• The left column shows the names and indexes of the array
• On the right is the data values stored in the array
• Like a variable, each array "slot" holds one value at a time
• We reference individual items by a name and index number 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
• We will discuss how to use non-numerical indexes later in this lesson

#### Check Yourself

1. An array is a ________ of data values organized using a ________ name.
2. The name for each data value in an array is ________ or item.
3. Access to an item in an array is through the use of a(n) ________ inside of square brackets.
4. True or false: each array element can store any number of values.

### 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 an array element like any other variable:
```echo "\$numbers[0], \$numbers[1], \$numbers[2]";
```
• By default, arrays indexes start at zero (`0`)
• PHP allows you to assign values without putting 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
• The following example assigns three values one after another without specifying an index:

``` <?php // Creating an array \$numbers[] = "zero"; \$numbers[] = "one"; \$numbers[] = "two"; // Reading 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 starts numbering array indexes at 0
• For example:

``` <?php // Creating an array \$numbers = array("zero", "one", "two"); // Reading values echo "\$numbers[0], \$numbers[1], \$numbers[2]"; ?> ```

#### Check Yourself

1. True or false: array variables must be dec;ared in advance.
2. By default array indexes start at ________ when no index is specified.
3. The following statement ________.
```\$foo = array("bar", "baz", "qux");
```
1. Creates an empty array named "foo"
2. Creates an array of 3 elements with the values of "bar", "baz", "qux" assigned to elements 0, 1 and 2.
3. Creates an array of 3 elements with the values of "bar", "baz", "qux" assigned to elements 1, 2 and 3.
4. Creates an array of 10 elements with the values of "bar", "baz", "qux" assigned to elements the first three elements.

### 8.3.3: Selecting Array Items

• Individual array elements are read using the array name and an index
• The array operator `[]` contains 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]; ?> ```

• PHP lets you 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`

#### Check Yourself

1. The number inside of the square brackets of an array is called an ________ or subscript.
2. The first element in any array has an index value of ________.
1. -1
2. 0
3. 1
4. 2
3. Of the following, ________ correctly access the fifth element of an array named "foo".
1. `foo[5]`
2. `foo(5)`
3. `foo[4]`
4. `foo.array[4]`
4. If you declare an array with 100 elements, the index number of the last element is ________

### 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
• Note 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>"; } ?> ```

• Notice the use of `\$i++` as a shortcut for adding one to a variable

#### Using `foreach`

• Another way to access each element of an array is the foreach loop statement
• Syntax:
```foreach (\$arrayName as \$varName) {
//loop body
...
}
```
• Where `\$arrayName` is the name of the array and `\$varName` is the variable that each array item is assigned to in order
• The `foreach` loop automatically assigns `\$varName` the next value in the array for each loop iteration
• Note that `foreach` works only with arrays

#### 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>"; } ?> ```

• Notice that each array item is accessed and displayed in order

#### Check Yourself

1. To determine the size of an array, you can use the function ________.
1. size()
2. length()
3. items()
4. count()
2. When accessing array elements with a for-loop, the loop counter variable is often used to calculate the array ________.
3. True or false: since the size of an array is always one more than the number of the highest element, the `for`-loop test condition uses the less-than operator (<).
4. With a ________ loop you do not need a counter variable.

### 8.3.5: Associative Arrays

• Arrays indices in PHP can be strings rather than numbers
• The string value is used to look up the location of the data value
• A common use for such an array is a dictionary of words with associated values

#### Creating Associative Arrays

• The following code creates an associative array
```\$ref['Abel'] = "Son of Adam";
\$ref['Baker'] = "One who cooks food in an oven";
\$ref['Charlie'] = "Nickname for Charles";
```
• Notice that the index is a string and not a number
• Each index must be unique
• We can create associative arrays with the `array` function as well
• 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
`\$ref['Abel'] = 100;`

#### 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>"; } ?> ```

#### Check Yourself

1. An array that allows non-numerical indexes in known as an ________ array.
2. True or false: associative arrays allow duplicate indexes.
3. True or false: a foreach loop works with non-numerical indexes.

### 8.3.6: Functions for Working With Arrays

• Like the PHP mathematical functions, 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

#### Check Yourself

1. True or false: to display an entire array, you can call the `print_r()` or `var_dump()` functions.
2. To determine the number of elements in an array, call either the ________ or ________ functions.
3. To test if an array element exists, call the function ________.
4. To remove an array element, call the function ________.

### Exercise 8.3

In this exercise we explore how to use arrays in PHP.

#### Specifications

1. 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>
<body>
<?php
// Enter your PHP code here

?>
</body>
</html>
```
2. 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.

3. 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.

4. 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.

5. 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.

6. 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.

7. 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.

8. 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.

9. 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.

10. Save your final `arrays.php` file to submit 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.

### 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

1. In an array, each individual data value has an that distinguishes it from other values in the array.
2. Given the code `\$myArray = array("first", "second");`, which of the following prints the word "first"?

3. A good way to display information about arrays or other variables is to use `var_dump(\$varName)`.

#### Check Yourself

1. What is an array? (8.3.1)
2. Why do we use arrays? (8.3.1)
3. What is an array index? (8.3.1)
4. What are two ways you can create and initialize an array? (8.3.2)
5. What statement would you use to create an array named `\$colors`? (8.3.2)
6. 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)
7. What expression would you use to return the third value from the array `dayNames`? (8.3.3)
8. How do you display an array using a loop? (8.3.4)
9. True of false? You can use string values as the index of an array. (8.3.5)
10. What is a good way to display information about an array for debugging purposes? (8.3.6)
11. If you want to know how many elements are in an array, what function can you use? (8.3.6)
12. If you want to remove an element from an array, what function can you use? (8.3.6)

## 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

### 8.4.1: Using Arrays for Multiple Form Values

• Arrays can help to generate checkboxes and selection lists
• In addition, arrays can help to process values received from checkboxes and selection lists sending multiple values
• We need arrays to process the form data because multiple checkboxes can have the same name:
```<input type="checkbox" name="pref[]" value="ASP"> ASP
<input type="checkbox" name="pref[]" value="JSP"> JSP
```
• Also, a selection list can be set up to accept multiple values using the `multiple` attribute
```<select name="sections" multiple>
```
• Both generating and processing form elements using an array are shown in the following examples
• Note the use of square brackets (`[]`) in the form name
• We need the square brackets in the form name to tell PHP to process the items as an array

#### 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

• Note the use of the empty() function to test if a variable has a value assigned
`if (empty(\$_REQUEST['pref']))`
• We use `empty()` to test if the expected data was filled in by the user
• Another useful function for testing variables is isset()
• Tests to see if a variable exists or not
• Also note that `print_r()` and `var_dump()` are good functions to use when debugging forms
• For example, to view all the variable data sent from a browser use:
```var_dump(\$_REQUEST);
```
• Insert the above code near the top of your script that receives the form data to see all the form values submitted by the user
• We will explore the use of arrays with a selection list later in the exercise

#### Check Yourself

1. True or false: some HTML form elements can produce multiple values.
2. True or false:Adding square brackets [ ] to the name of an input field causes PHP to generate an array of values.
3. To test if a variable has been assigned a value, call the function ________.
4. To test if a variable exists, call the function ________.

### 8.4.2: Fetching Data from MySQL in Arrays

• You can use arrays to extract MySQL data from a result set
• PHP provides mysql_fetch_array() to read result set data into arrays
`\$row = mysql_fetch_array(\$result, MYSQL_BOTH);`
• Similar functions are:
• Using this technique, PHP can extract an entire row of data from the result set
• Each column (field) of the row is contained in the elements of the array
• Usually, these functions provide better performance than mysql_result()

#### Checking the Result Set

• PHP provides other useful functions for processing result set data
• You can use mysql_num_rows() to count the number of rows in query results
`\$numRows = mysql_num_rows(\$result);`
• Also, you can use mysql_num_fields() to count the number of columns in query results
`\$numRows = mysql_num_fields(\$result);`
• With loops, you can use these functions to make a query and display the results

#### 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 \$rowwhile (\$row = mysql_fetch_assoc(\$result)) {    // Inner loop displays each column of \$row    echo "<p>";    foreach (\$row as \$item) {        echo "\$item ";    }    echo "</p>\n";}// Clean upmysql_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?

#### Check Yourself

1. Of the following, ________ is NOT one of PHP's function to read result set data into an array.
1. mysql_fetch_array()
2. mysql_fetch_row()
3. mysql_fetch_assoc()
4. mysql_fetch_result()
2. To count the number of rows in a result set, call the function ________.
3. To count the number of columns (fields) in a result set, call the function ________.

### 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
• As an alternative to a table, we can use `div` or `span` elements

#### 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 tableprint "<table border=\"1\">\n";while (\$row = mysql_fetch_assoc(\$result)) {    echo "<tr>\n";    foreach (\$row as \$item) {        echo "<td>&nbsp;\$item</td>\n";    }    echo "</tr>\n";}print "</table>\n";// Clean upmysql_free_result(\$result);mysql_close(\$dbCnx);?> ```

#### Check Yourself

1. True or false: a way to organize data in HTML is to use a table.
2. As an alternative to a table, use `div` and ________ elements.

### 8.4.4: Adding Column Names with Meta-data

• One thing missing from the table is names for the columns
• We could add this information by hand
• However, a better way is to use MySQLs meta-data

• MySQL keeps data about its databases, table structure and records
• For example: database names, table names, column names, column types, etc.
• When we make a query, the result set contains information about the data
• This information is known as the result-set metadata
• PHP provides a number of functions to access the result set metadata
• One function is called mysql_field_name() which returns the name of the specified column (field) from the result set
```for (\$i = 0; \$i < \$count; \$i++) {
print "<th>".mysql_field_name(\$result, \$i)."</th>\n";
}
```
• Another function is mysql_field_table, which returns the name of the specified table for a column (field) from the result set
`mysql_field_table(\$result, 0)`
• We can use this meta-data to provide table names and field names

``` <?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 nameecho "<h4>Table: ";echo mysql_field_table(\$result, 0);echo "</h4>\n";echo "<table border>\n";// Show the column names as table headingsecho "<tr>\n";\$count = mysql_num_fields(\$result);for (\$i = 0; \$i < \$count; \$i++) {    echo "<th>&nbsp;";    echo mysql_field_name(\$result, \$i);    echo "</th>\n";}echo "</tr>\n";// Show the result set data using HTML tableswhile (\$row = mysql_fetch_assoc(\$result)) {    echo "<tr>\n";    foreach (\$row as \$item) {        echo "<td>&nbsp;\$item</td>\n";    }    echo "</tr>\n";}echo "</table>\n";// Clean upmysql_free_result(\$result);mysql_close(\$dbCnx);?> ```

#### Check Yourself

1. Data describing data content is referred to as ________.
2. To discover the name of a table in a result set, call the function ________.
3. To discover the name of a column in a result set, call the function ________.

### 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

1. 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. For more information see lesson 6.3.1: Connecting to a MySQL Database.

2. 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>
<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.

3. 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());
```

4. 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.

5. 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.

6. 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);
```

7. 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.

8. 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>
<body>
<h1>Product Report</h1>
<?php
var_dump(\$_REQUEST); // replace this statement

?>
</body>
</html>
```
9. 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.

10. Replace the `var_dump()` function call with the following statement to retrieve the value of "prodselect" submitted by the form:
```\$id = \$_REQUEST["prodselect"];
```

11. 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());
```

12. 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.

13. 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.

14. 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);
```

15. 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.
16. Save both your final `prodselect.php` and `prodreport.php` files to submit to Blackboard as part of assignment 8.

#### Check Yourself

1. True of false? Checkboxes and selection lists can submit multiple values to a form processing script. (8.4.1)
2. What PHP functions can you use to extract and entire row of data from a result set? (8.4.2)
3. In what format is the extracted returned from these functions? (8.4.2)
4. What is meta-data? (8.4.4)

### 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

1. Meta data is data about data.

2. To find out how many rows of data were returned in a results set, you use the function .
3. Which of the following is not one of the three functions for placing a row of data from a results set into an array?

## Wrap Up

Due Next:
A8-Query and Report (4/23/12)
Quiz 8 and Discussion 8 (4/23/12)
When class is over, please shut down your computer if it is on
Home | Blackboard | Syllabus | Expectations | Schedule
Project | Help | FAQ's | HowTo's | Links
Last Updated: May 13 2012 @16:29:43