Chapter 6 - Creating and Using Arrays

By: Albert Ritzhaupt

 

 


Chapter Topics

Why an Array? 

Arrays are extremely handy tools to the web programmer.  An array is a set of sequentially indexed elements generally having the same type of data.  Until now, all of our variables were capable of storing a single value.  A variable that holds a single value is adequate for most situations.  Sometimes we might need a structure that is capable of holding more than a single value.  For instance, think about the calendar months in a year: January to December.  In our program, we could create twelve variable for each month.  However, this would be cumbersome and difficult to manage.  Look at the example below.

 $month1 = "January";
$month2 = "February";
$month3 = "March";
$month4 = "April";
$month5 = "May";
$month6 = "June";
$month7 = "July";
$month8 = "August";
$month1 = "September";
$month10 = "October";
$month11 = "November";
$month12 = "December";
//prints January
echo $month1;

To create a list of months, we would need to create twelve unique variables.  Additionally, to use any of the variable you must reference them by the specific name.  By using arrays, we only need to create one variable (it is not exactly a variable) that can be referenced throughout the program.  Look at the example below.

 $months = array("January", "February", 
"March", "April", "May", "June", "July",
"August", "September", "October",
"November", "December");
//prints January
 echo $months[0];

As you can see, we now are only using one variable  to reference multiple values.  This will make your life easier as a programmer because now you do not have to maintain twelve different variable.  Notice that we use the index zero to reference the month January.  Arrays are generally in the range of 0 to N-1, where N is the number of elements in the array.   

"PHP arrays have many advantages. First of all, they're flexible. You can store as many items as you need, and work with all of them from one variable. In addition, you can work with a single element at a time by using the index value, or you can work with all of the elements. There are many built in PHP functions to help you loop through all the values in the array, count them, shuffle them, sort them, and more (Arrays 101, 2005)."

Now that you can see the value in arrays, we need to spend a little time learning how to reference specific value and the syntax of arrays.

back to top

Creating Arrays in PHP

There are a number of ways to create arrays in PHP.  You have already seen one (calendar months) of the ways you can create arrays in PHP.  In that specific approach, an array of 12 elements is created, indexable from 0 - 11.  For a visual example, look at the table below.  To index the month of June, we would use the value 5.  To reference the month of October, we would use the value 9 and so forth.  The table below provides you an example of how the information could be visualized.

Index Value
0
January
1
February 
2
March 
3
April 
4
May
5
June 
6
July 
7
August 
8
September 
9
October 
10
November 
11
December 

This is one way that an array could be created.  The statement array(x, ...) is actually a function used to create the array.  You could also create an array by simply declaring and initializing the array.  The figure below provides an example.  Here, PHP increments the index automatically for you.

 $months[] = "January";
 $months[] = "February";
...
$months[] =  "December";

The most widely accepted way of creating an array is by specifying the value of the index.  This is probably a better way for a beginner, too.  The figure below provides an example of how you could explicitly create the array.

 $months[0] = "January";
 $months[1] = "February";
...
$months[12] =  "December";

Okay, so you should have a basic understanding of how to create a one-dimensional array.  That's right, the array has only one dimension as of now.  Later in this chapter we will look at N-dimensional arrays which are a little more tricky.  Next we are going to see how for-loops can be used to traverse the elements of an array.

back to top

Traversing the Elements of an Array

For-loops and arrays go together like peanut butter and jelly.  The for-loop can be used to increment a variable that serves as the index of the array.  What's more, PHP has a function available to you for ascertaining the length of the array that can be used as the condition in the for loop.  For example, consider the $months array we have been developing thus far.  The figure below shows the source code that would enable you to traverse all the months.

<?php
//create the calendar array
$months = array("January", "February",
"March", "April", "May", "June", "July",
"August", "September", "October",
"November", "December");

//gets the length of the array
$length = count($months);

//traverses the array and prints
for($i=0; $i < $length; $i++)
{
echo "$months[$i]<br>";
}
?>

As you can see, we first create the array, get the length of the array dynamically using the count function, and then use a for-loop to traverse all the elements of the array.  For an example of the output, look at the link below.

>>Program Example 1

back to top

Checkboxes and Arrays

One frequent application of an array is when you need to capture the values of checkboxes from an HTML form.  Checkboxes are used when multiple values can be selected.  For instance, if you asked someone to list the types of pets they own.  It is likely that an individual will own no pets, one pet, two pets, etc.  If you wanted to get all the pets an individual owns, you could use a set of checkboxes.  Consider the source code in the figure below.

<html>
<form action="example2.php" method="post">
Dog: <input type="checkbox" name="pets[]" value="Dog"><br>
Cat: <input type="checkbox" name="pets[]" value="Cat"><br>
Fish: <input type="checkbox" name="pets[]" value="Fish"><br>
Bird: <input type="checkbox" name="pets[]" value="Bird"><br>
Snake: <input type="checkbox" name="pets[]" value="Snake"><br>
<input type="Submit" value="Pets">
</form>
</html>

In the source code above, we create a simple form with five different pets.  The user has the option of choosing any number of these pets.  Notice in the name attribute that braces [] are placed after the name.  This is required in order for PHP to read the information.  The source code below is the PHP program that will allow you to manipulate the values.

<?php
//capture list of pets
$pets = $_POST['pets'];

//gets the length of the array
$length = count($pets);

//traverses the array and prints
for($i=0; $i < $length; $i++)
{
echo "$pets[$i]<br>";
}
?>

As you can see, the process is very similar to the previous example.  You simple capture the values, get the length of the array, and print the values.  An example program can be seen below.

>>Program Example 2

back to top

An Alternative For-Loop

Some prefer using the method shown in example 1 to traverse the elements of an array.  However, PHP has a handy for-loop specially designed for traversing arrays.  This loop becomes increasingly important when we do not use a sequential list of values as the index of the array.  For example, one could index an array with the string "FL" to correspond to the value "Florida".  The other method would not allow you to index the array this way.  The source code for the alternative for loop can be seen below.

<?php
//create the calendar array
$months = array("January", "February",
"March", "April", "May", "June", "July",
"August", "September", "October",
"November", "December");

//traverses the array and prints
foreach($months as $month)
{
echo "$month<br>";
}
?>

Notice that we do not have to worry about identifying the length of the array or increment a counter for this approach.  Also, notice that the loop states the array to reference and a variable name to reference the current value.  In the example above, the array is $months and the variable used to reference the current value is $month.

back to top

Sorting the Elements of an Array

Sometimes it is useful to sort the values in an array.  For example, if an array contained a list of names, you may want to list the names in alphabetical order.  PHP has twp great functions named sort and rsort that specifically addresses this problem. The sort function will sort the list in ascending order while the rsort will sort the list in descending order.  Look at the example source code below.

<?php
//create the calendar array
$months = array("January", "February",
"March", "April", "May", "June", "July",
"August", "September", "October",
"November", "December");

//prints original list
echo "<br>original list<br>";
foreach($months as $month)
{
echo "$month<br>";
}

sort($months);
//prints sorted list
echo "<br>sorted list<br>";
foreach($months as $month)
{
echo "$month<br>";
}

rsort($months);
//prints reverse sorted list
echo "<br>reverse sorted list<br>";
foreach($months as $month)
{
echo "$month<br>";
}
?>

We are using the same code from the previous section with two fundamental differences.  The sort function is called by passing the $months array and the process is repeated for the rsort function.  An example of the output of this program can be linked to below.

>>Program Example 3

back to top

N-Dimensional Arrays

The last topic we are going to address is N-dimensional arrays.  Thus far the arrays we have used are one-dimensional.  However, we can create arrays with many dimensions.  For simplicity sake, we are going to stick with two-dimensions because they are easy to visualize and understand.  Consider the table below.  Suppose this is a table that shows the employee that will work in a given section during a given shift at a restaurant.

Breakfast Lunch Dinner
Index 0 1 2
Section 1 0 James Mark April
Section 2 1 Bob Paul Michelle
Section 3 2 Rachel Derick Tom

We could create a two-dimensional array to hold this information that can be later referenced in our program.   Assume we wanted to create a program that will determine which employee is working provided a section and a shift.  

<html>
<form action="example4.php" method="post">
Section: <select name="Section">
<option value="0">Section 1
<option value="1">Section 2
<option value="2">Section 3
</select><br>
Shift: <select name="Shift">
<option value="0">Breakfast
<option value="1">Lunch
<option value="2">Dinner
</select><br>
<input type="Submit" value="Get Employee">
</form>
</html>

The form contains two drop down menus: one for shift and one for section.  The user can select a section and shit, press submit, and determine which employee is working.  The source code for the PHP program can be seen in the figure below.

<?php
//creates the 2 x array
$employee[0][0] = "James";
$employee[0][1] = "Mark";
$employee[0][2] = "April";
$employee[1][0] = "Bob";
$employee[1][1] = "Paul";
$employee[1][2] = "Michelle";
$employee[2][0] = "Rachel";
$employee[2][1] = "Derick";
$employee[2][2] = "Paul";

//gets the values
$section = $_POST['Section'];
$shift = $_POST['Shift'];

//references the value and prints.
$emp = $employee[$section][$shift];
 echo "<h2>$emp works!</h2>";

?>

It is important to notice that the section is the row and the shift is the column.  Therefore, when referencing a two dimensional array, one first references the row, and then column (eg. array[row][column]).  An example of this program can be linked to below.  Notice the relationship between the row and column based on the options you select.

>>Program Example 3

back to top

A Final Note

Arrays in PHP are not exactly arrays.  In computing terminology, arrays are actually ordered maps in PHP.  From a practical perspective, they can be treated similarly.  However, it is important to note the difference.  For more information about how PHP handles arrays, please take a look at the arrays manual.

back to top

Your Sixth Program

This section will provide the steps for you to create your sixth PHP program. 

  1. First create a file named "sixth.html" in a directory that is recognized by the web server. The file should contain the following information:

    <html>
    <form action="program6.php" method="post">
    Row: <input name="rows"><br>
    Column: <input name="cols"><br>
    <input type="Submit" value="Build">
    </form>
    </html>

  2. Now let's create the source code for the program.  Create a file named "program6.php" in the same directory as "sixth.html".  The file should contain the following information:

    <?php
    $rows=$_POST['rows'];
    $cols=$_POST['cols'];

    //builds a matrix of random numbers
    for($i; $i < $rows; $i++){
    for($j; $j < $cols; $j++){
    srand ((double) microtime( )*1000000);
    $matrix[$i][$j] = rand(1,100);
    }
    }

    //prints a matrix of random numbers
    for($i; $i < $rows; $i++){
    for($j; $j < $cols; $j++){
    $matrix[$i][$j] . " ";
    }
    echo "<br>";
    }
    ?>

  3. After you have created the file and put the information into the files, save your work, and change the permissions of the files to:

    prompt$: chmod 704 fifth.html
    prompt$: chmod 705 program5.php

  4. Open the URL to the location where you saved the file (sixth.html) and you should be able to play the number game.

It is important to notice that this program first constructs a two-dimensional array, and then prints the matrix structure.  The matrix is loaded with random number in the range of 1 - 100.  This is accomplished using the rand() function with two parameters (min, max).  To do this, you must first call the srand() function uses the system time as a seed to generate the random number.

Congratulations! You have completed the sixth chapter. You can now take the online assessment, complete the sixth activity, and move to the next chapter. 

>>Take the Online Quiz

back to top

Activity 6

Build a simple program similar to the one found in example 3.  First build an HTML form to accept three fields: Position Type, Department, and Hours Worked.  Position Type and Department should follow the matrix below as drop down menus.  The PHP program should calculate the weekly pay based on the salary table below and the hours worked.  Take into account overtime and print the Department, Position, Hours Worked, Hourly Rate, and Weekly Pay to the screen.  

Employee Supervisor Manager
Index 0 1 2
Operations 0 6.26 8.50 12.50
Accounting 1 10.50 18.75 22.75
Human Resources 2 9.50 17.55 19.25

back to top

Chapter References 

back to top

 

Copyright 2005 Albert Dieter Ritzhaupt. All Rights Reserved.