Warning! The Web site for this class is in beta form.

# Laboratory: Arrays in PHP

Summary: PHP arrays represent a curious hybrid of indexed arrays (as in Java or C) and dictionaries (called associative arrays in PHP). This laboratory exercise provides experience with both aspects of PHP arrays.

Prerequisites: Basic PHP.

References:

Contents:

## Preparation

a. Log in to your MathLAN workstation. (Of course, you've probably already done that if you're reading this laboratory.)

b. Open a terminal window into which you can type commands.

c. Open a Web browser so that you can explore the pages that you create.

## Exercises

### Exercise 1: Indexed Arrays

Consider the following PHP statement.

```   \$month = array ('January', 'February', 'March', 'April',
'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December');
```

a. Put the statement in an HTML/PHP script.

b. Write a For loop that prints these months in order. Note that the months can be retrieved as `\$month[0]` ... `\$month[11]`.

### Exercise 2: Sorting Out Sorting

a. Add a line to your code to place the months in alphabetical order. For example, you might write

```   sort(\$month);
```

b. Predict the effect of this command on the output from the For loop described above.

c. Check your answer experimentally.

### Exercise 3: Iterating Elements with `foreach`

The For each loop provides another way to cycle through the values in an array. We often use such a loop when the index of each item is not of particular interest.

```    foreach (\$month as \$item) {
echo \$item ;
echo "<br>";
}
```

Confirm that this code works as you might expect.

### Exercise 4: Associate Arrays

While we are used to arrays that are indexed by integers (and, often, integers starting at 0), many scripting languages provide arrays that can be indexed by strings (or by arbitrary values). Different designers use different names for these arrays. Some call them dictionaries. Some reflect on the typical implementation and call them hash tables. Some generalize and just call them tables. Still others call them associative arrays, because they act much like arrays, and they associate one value with another. This last term is the standard PHP name for such arrays.

Consider the following array initializations:

```   \$monthDays = array ('January'   => 31, 'February' => 28,
'March'     => 31, 'April'    => 30,
'May'       => 31, 'June'     => 30,
'July'      => 31, 'August'   => 31,
'September' => 30, 'October'  => 31,
'November'  => 30, 'December' => 31);
```

You can access various elements of this array as `\$monthDays['January']` ... `\$monthDays['December']`.

a. Using this array and your previous (unsorted) array of month names, write a loop that prints out a table of the number of days in each month.

b. Using this array and your previous array of month names, arrange to print out all the months with 30 days. (Assume that you do not know in advance which months have 30 days.)

### Exercise 5: Iterating Associative Arrays with `foreach`

One can access both key and value of an associative array with a loop like

```    foreach (\$monthDays as \$item => \$days) {
....
}
```

Using this form, arrange to print a table of the number of days in each month.

### Exercise 6: Extrema

Here is a set of month data for a fictitious country that does not use the twelve-month roman calendar.

```   \$monthDays = array ('Splorch'     => 23, 'Sploo'       => 28,
'Splat'       =>  2, 'Splatt'      =>  3,
'Spleen'      => 44, 'Splune'      => 30,
'Spling'      => 61, 'Slendo'      => 61,
'Sploctember' => 31, 'Splictember' => 31,
'Splanet'     => 30, 'TheRest'     => 22);
```

a. Write a program that finds the number of days in the shortest month and the longest month in this calendar. Ideally, you will do so without relying on loops. Instead, you should take advantage of built-in functions for exploring and manipulating arrays. You may wish to refer to the PHP documentation to identify the functions that determine the minimum and maximum values within an array.

b. Write a program that finds the total number of days in a year with this arrangmenet of months. Again, you should try to do so without relying on explicit loops. (You certainly should assume no knowledge of the underlying data.)

c. Write a program that prints the name of the shortest and longest month.

### Exercise 7: Sorting Associative Arrays

Consider your program that prints out the table of months and the corresponding number of days in that month.

a. Suppose we arranged to sort the array before printing the table. What effect do you expect such sorting to have on the output?

b. Check your answer experimentally.

### Exercise 8: The `\$_GET` and `\$_POST` Arrays

As you may have noted, `\$_GET` and `\$_POST` are associative arrays that PHP fills in automatically. Write a simple program that prints out the contents of each array as a key/value pair.

### Exercise 9: The `\$_SERVER` Array

Another important prefilled array is `\$_SERVER`, which includes lots of information about your server and about the HTTP request.

a. Write a script that prints out the contents of that array.

b. Pick six interesting elements of that array and explain their purpose. In doing so, you may find it useful to refer to the appropriate section of the PHP Manual

c. Be prepared to share what you've learned with your classmates.

## History

10 August 2008 [Henry Walker]

• Created.

19 September 2008 [Henry Walker]

12 September 2010 [Samuel A. Rebelsky]

• Reformatted.
• Renumbered exercises and added exercise titles.
• Added exercise on sorting associative arrays. (That exercise was previously part of a longer "Read and understand this code" exercise.)
• Added the Spl-months execise.
• Excised materials on log files. (Log files will be a separate lab.)
• Added preparation section.
• Lots of minor rewrites and edits.
• This version available at `http://www.cs.grinnell.edu/~rebelsky/Courses/CSC325/2010F/Labs/php-arrays-lab.html`.

Disclaimer: I usually create these pages on the fly, which means that I rarely proofread them and they may contain bad grammar and incorrect details. It also means that I tend to update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.

This document was generated by Siteweaver on Mon Nov 29 09:06:18 2010.
The source to the document was last modified on Sun Sep 12 14:09:15 2010.
This document may be found at `http://www.cs.grinnell.edu/~rebelsky/Courses/CSC325/2010F/Labs/php-arrays-lab.html`.

You may wish to validate this document's HTML ; ;

Samuel A. Rebelsky, rebelsky@grinnell.edu

Copyright © 2010 Henry Walker and Samuel A. Rebelsky. Please contact us for permission to reuse materials.