spacer
Home News Links People Catalog
spacer
activepages
spacer

Week 5: Arrays, Functions and the "foreach" loop

Introduction to Lists

When you think of a list on the Web, you likely think of ordered and unordered lists implemented by the <OL></OL> and <UL></UL> HTML elements. Within both of these elements, the LI element produces a list item. This use of the word list is the common use of the word list in everyday conversation. For example: "Did you add carrots to the shopping list?". Very rarely does someone create an ordered shopping list that matters (perhaps ordered in terms of importance should money be short makes sense - or how about in order of how they are spatially encountered in the grocery store?).

Well, computer scientists have a very specific use of the word list in mind when they refer to a list as an organized container of information existing in computer memory or on a storage medium (your hard drive, for example). Let's use the shopping list as a container of information and look at how PHP creates, stores, and modifies a list for you to use in your Web pages. The biggest advantage of using a list is that it is dynamic. You can have four items on your shopping list one week and forty the next week and still use the same PHP code for both to present it on a Web page. When you delete an LI element from within an HTML list the Web browser automatically renumbers for you - but you have to get the LI content on the page by typing or copying and pasting text into each LI element. When w use PHP, we can connect to a database or a stream of data from any source and present the information in a list without re-typing it. A popular way to generate a list is by using an array of information in a program to build the list (see example 1 below). An array is a broad computing concept while a list is a more specific concept. I rarely use use this list() interface in PHP so I don't want you to spend too much time on it.

Lists are very popular for certain types of processing. There is a clever programming language called LISP that works very effectively with lists as the main container for all the variables being used in computation. But, we'll only need to use generic arrays for our work in this class. The list is more a presentation concept as you might expect since we are generating HTML with our PHP code. Take a look at these three examples, note that list() exists in the PHP language, but then move on to the array information following them quickly. Example 3 has useful context when you think of nested lists in HTML pages (OL elements inside of UL elements, for example).

List Examples

Example #1 Basic PHP list() processing

<?php

$info 
= array('coffee''sugar''milk''carrots');

// Listing all the variables
list($drink$additive$dairy$vegetable) = $info;
echo 
"I need $drink with $additive and $dairy and some $vegetable for afternoon snack.\n";

// Listing some of them
list($drink, , 
$vegetable) = $info;
echo 
"$drink and $vegetable.\n";

// Or let's skip to only the third one
list( , , $dairy) = $info;
echo 
"Gotta have $dairy in my hot drinks!\n";

// list() does *not* work directly with strings - therefore, this is not valid:
list($bar) = "abcde";

?>

Example #2 Presenting a list() as HTML output

<table>
<?php

$info = array('coffee''sugar''milk''carrots');
list($drink$additive$dairy$vegetable) = $info;

    echo " <ul>\n" .
         
"   <li>$drink</li>\n" .
        
"   <li>$additive</li>\n" .
        
"   <li>$dairy</li>\n" .
         "   <li>$vegetable</li>\n" .
         
" </ul>\n";
?>

Example #3 Using nested list()

<?php

list($a, list($b$c)) = array(1, array(23));
echo $a." ".$b." ".$c;

?>

Arrays

Wikipedia provides a pretty accessible discussion of the word Array as I am referring to it in this class. Arrays hold data in convenient ways for us to refer to a collection in our PHP code. You are guaranteed that each item in the array has the same data type (and thus is available to the same kinds of processing). It is typical to think first and foremost of arrays as containing contiguous information in computer memory or a storage medium (that's the main point to think about as we use them). The contiguous storage kind of array discussed on the Wikipedia page may alternatively be called a vector, list, or table depending on how the data is intended to be used. Vectors are used a lot in scientific processing. Tables are used a lot in generic information processing. We'll see later on in this course that databases are comprised of a series of tables and that table is a keyword we use a lot when working with the data managed by a database. When we are designing our dynamic Web pages and don't yet have access to a database, we can put data into arrays temporarily on our page to test our presentation - then connect to our database when we are sure of what we need our database to contain. The point is, when we do that, we just move the tables of data from our page to the database - the structure is similar either way. And, as a result, arrays are very practical for us to learn in a beginner's course - even though there is a lifetime of continued learning you can pursue with arrays as an important concept in complex data structure theory. I found my computer science course on arrays and data structures to be one of the most fascinating and insightful courses I have ever taken - most of my peers felt the same way. So, if you like working with arrays, you should pursue further study beyond just the practical information I cover here.

Dynamic Arrays (using the array() function)

A dynamic array is one that changes in size depending how we use it after we have created it. A list is dynamic when we add a new item to it or delete an item from it. So, it makes sense to use a dynamic array for managing lists. Look back up at the list() discussion above. We use the array() function to populate our lists. The array() function can be used to generate dynamic arrays. You might be asking yourself why you wouldn't want to use dynamic arrays all the time? There is a lot to think about in that answer, but I'll provide two simplified reasons here: First, when you create a static array and let PHP know you won't be changing it (and therefore you can't thereafter), PHP can perform some optimization work in preparing for its use - knowing it will never have to re-calculate that optimization. Its use can then be faster for the long term. Second, when you use a dynamic array, PHP has to make new room on in computer memory or in storage memory in order to store the new data you put in the array. In many applications, it is best to know you are going to run out of memory up front before going through a lot of effort to run out of memory down the road. You set up the memory once at the beginning to stablize the system and then never have to worry or slow down the system to generate it after that point in time. In terms of Web pages, we rarely use so much information as to run out of computer memory (unless our computers are running all kinds of other applications at the same time) and so I use static arrays all the time even if I waste memory by not actually putting meaninful data in all of the array I have created. Computer scientists call these kinds of decisions size versus speed trade-offs. Enough said for our needs. Just note there are lots of things you can do with arrays once you've created them.

Let's look at some simple examples of using dynamic arrays. Before we start, let me say that a very good page on the Web to give you examples of all aspects of arrays is http://www.php.net/types.array. When you can understand all these examples, you'll be well on your way to being an arrays guru. You don't need to be a guru for this class though.

Array Examples - Dynamic

	<?php
// create a basic dynamic array with four numbers as elements in the array $my_numbers = array(43, 32, 56, 12); // insert a new fourth item in the list array_splice($my_numbers, 3, 0, 17); // add a new item to the end of the list array_push($my_numbers, 29); var_dump($my_numbers); echo "<br/ ><br/ >"; for ($i=0; $i<count($my_numbers); $i++) { echo $my_numbers[$i]; echo "<br/ >"; } // delete the last item from an array array_pop($my_numbers); echo "<br/ ><br/ >"; foreach ($my_numbers as $element) { echo $element; echo "<br />"; } ?>
produces the result:

array(6) { [0]=> int(43) [1]=> int(32) [2]=> int(56) [3]=> int(17) [4]=> int(12) [5]=> int(29) }

43
32
56
17
12
29


43
32
56
17
12

Much of this is pretty conventional and familiar to me based on other programming languages. Of interest to me is the array_splice() function as I haven't seen that before. You can treat arrays as if they contained frames of film and then insert pieces of one array into another. Thinking of it that way, the word splice makes reasonable sense, but I haven't thought of film editing in the context of arrays before. Popping and pushing help you treat your array like a stack which is a convenient programming concept used a lot in solving problems efficiently. For now, take a look at the various ways you can print out the contents of an array (you can print out an array to look for errors in your code). The var-dump() function does a very thorough job of describing the array's contents but might be more technical than you need (it includes the datatype for each data item being printed). Using a for loop to print out an array is standard for almost any programming language. The foreach() function has been added to most programming languages lately and so is good to learn as well (it is easier to read than for loops in many cases once you are used to them). I'll delay talking about using the data in dynamic arrays in your programs until after I show you the same features with a static array (since accessing values in the array is similar for both dynamic and static arrays).

Static Arrays with Numeric Indices and the Array Access Operator

You'll get used to seeing square brackets and an integer (whole number) index when working with static arrays. When you see something like $row[14] in a PHP program, you'll know that the program uses many instances of a similar variable type - and you'll expect there to be at least 14 other instances active in memory (or on a storage drive). Array indexing starts with the number 0 and then counts 1, 2, 3, 4 ... To define a static array, you assign values to the members of the array using the numeric index:

$names[0] = "Edie";
$names[1] = "Nick";
$names[2] = "Emily";

The data type rules apply to the array as a whole just as they would a dynamic array or a single variable. In this case above, all three members of the $names array are ready to be used as String variables. Computer Scientists start with the number zero in order to make memory management mathematics easier to calculate. Think about it this way: When the physical device that wants to read or write to an array needs to calculate how far to move to access a member of the array, it's already at the 0th member of the array and needs to move 0 bits or bytes from that position to access the first member (hence it conventionally having index [0]. To determine how far that device needs to move its reader to the $row[14] member, it only needs to move 14 times the size of the $row data type. If a $row variable is ten bytes, the reader moves 140 bytes to read that 15th static (sequential) member - it is the 15th (and not the 14th) member that is 14 units away. We often use an integer variable to initialize a static array in memory and then to perform any action on its members. You should be able to imagine multiple ways of doing either initialization or processing: Use a while loop, a for loop, a conditional statement, or any specialized statements like the foreach loop discussed further below. Arrays, like redundant and conditional processing, are core specialities of computer hardware that assist us humans tirelessly and reliably.

Take a look at our examples above, but using static arrays this time:

Array Examples - Static

<?php
// create a basic dynamic array with four numbers as elements in the array $my_numbers[0] = 43; $my_numbers[1] = 32; $my_numbers[2] = 56; $my_numbers[3] = 12; $my_numbers[4] = -1; $my_numbers[5] = -1; $my_numbers[6] = -1; // insert a new fourth item in the list $my_numbers[4] = $my_numbers[3]; $my_numbers[3] = 17; // add a new item to the end of the list $my_numbers[5] = 29; // print out the state of the array echo "<br/ ><br/ >"; for ($i=0; $i<count($my_numbers); $i++) { if($my_numbers[$i] > 0) { echo $my_numbers[$i]; echo "<br/ >"; } } // delete the last item from an array $my_numbers[5] = -1; echo "<br/ ><br/ >"; foreach ($my_numbers as $element) { if($element > 0) { echo $element; echo "<br />"; } } ?>
which again produces the result:

43
32
56
17
12
29


43
32
56
17
12

but this time we have to do some of the array processing ourselves - we use -1 as a sentinel to tell us when the array ends its meaningful data (most programmers might use null for a sentinel but the -1 is good for our class). We have to move some members (often with a loop if in the middle of a large array) in order to insert a new one. And, we have to initialize members we don't use initially so they exist when the time comes to use them. The result is that we write less flexible code, but we may get the benefit of faster processing under certain conditions (and we don't have to worry about running out of memory at run time). Many programming languages have nifty features to manipulate arrays using index mathematics - another interesting concept to play with if you want to better understand how computing hardware works. PHP does not require you to understand how the hardware works - you can better spend your time on making useful and attractive websites.

Associative Arrays

Arrays have long used integer indices for member access by convention (and to be more explicit in the data access mathematics). These indices often mean nothing to those who read your code except that there is some kind of order inherent in your data. Often, even that is misleading because there is no order intended - you just had to assign one arbitrarily because arrays required one. Dynamic arrays eliminate the index when manipulating the array, but can still use the index when trying to access an array member. When you see a line of code like:

$name[56] = "Davis, Renjay"

you don't know if the array was defined in a dynamic or static manner unless you refer to code elsewhere. It doesn't matter when you refer to a data location because it works the same way for read and write access once the location in memory has been assigned a name. You can eliminate the integer index though if you have a more useful system in place to manage the array memory. You can associate other labels to your array items. When you assign these labels instead of integers, you are by definition using an associative array. Associative arrays are very useful for data processing and since the Web is used so much as a data presentation medium, associative arrays are more common on the Web than in many other programming domains (contexts). Scientific processing, which uses a lot of matrices, vectors, and numeric arrays, typically avoids associative arrays because of other conventions that give added meaning to an array's whole number index.

Associative arrays work really well with data that naturally behaves well in a relational database like MySQL (the one we will use in class). Data in databases are held in tables of records (as we will see often in this class eventually). Records give a name to each item which is then referred to as an attribute of the record. An employee record typically has an ID, name, job_position, and salary associated with the record. The word 'associated' in that last sentence is exactly the passive use of the verb 'to associate' that is related to the adjective use of the word 'associative' when referring to an array.

You can create a single employee record as an associative array:

$employee['1217'] = array("Robert","Chen","Accounting",58234.50);

and then refer to the attributes of the record by referencing the associative array by record components offset index.

For example:

$employee['1217'][0] references employee 1217's first name attribute of "Robert"

You can then add another employee record using the first one as a template:

$employee['455'] = array("Lucy","Jones","Product Development",87106.00);

The associative key does not map to a specific integer offset so the order in which new employee records is created does not effect the organization of the array for access purposes. You use a key to create an array variable, you must use the key to get the values out of the array variable.

But, you can always iterate through all the arrays that have been produced with the same variable label through a foreach loop:

foreach ($employee as $empl) {
    echo $empl[1]."<br/>";
}


accesses all the employees names and prints them out to a Web page being processed by PHP.

So, the following PHP code segment:


<?php
	$name[56] = "Davis, Renjay";
	$employee['1217'] = array("Robert","Chen","Accounting",58234.50);
	echo $employee['1217'][0]."<br/><br/>";
	$employee['455'] = array("Lucy","Jones","Product Development",87106.00);
	foreach ($employee as $empl) {
    	    echo $empl[1]."<br/>";
	}
?>
Produces this result:
Robert

Chen
Jones

Associative Arrays and the Arrow Operator

You can create a single employee table as an associative array:

$employee = array("ID"=>array("1217"), "name"=>array("Bob Chen"), "dept"=>array("Accounting"), "salary"=>array(58234.50));

Because every member of an array must be of the same data type (a definitional characteristic of an array that we rely on when processing one), we have to use the dynamic array data type as our data type for objects in an array that we want to have different data types. This is a very important concept to master. We want to be able to process data reliably and appropriately. Arrays require that you put information into them in regular ways that help you or others use them reliably and appropriately. Even a laissez-faire language like PHP can't break that tradition without making programmers (including myself) upset. Instead, PHP offers other more flexible constructs for those times when you want to be more free form with data. I don't want to access an employee's salary and find that I can't calculate payroll taxes on it because it holds the value "executive" instead of a real number with which I can do multiplication. The array won't let me put that in there in the first place if I use the array structure that is allowed by PHP (which is a structure very similar to other languages by convention). Reading the above $employee data structure from left to right, I say an employee has an ID of type String (we don't do math on IDs so they usually are Strings), a name of type String, a department of type String and a salary of type double (that is double precision real number - the default unless we tell PHP otherwise when using a decimal point). I tell the array they are all of type array to be consistent with type (I defer the typing to inside the next level of array). Then, each array I create must only have data of the same type (which is guaranteed here because there is only one member in each array!).

My $employee array of arrays is not very useful as is because I only have one employee represented. I just have to add another member to each array to add a second employee:

$employee = array("ID"=>array("1217", "455"), "name"=>array("Bob Chen", "Lucy Jones"), "dept"=>array("Accounting", "Product Development"), "salary"=>array(58234.50, 87106.00));

and then a third for a third, a fourth for a fourth, etc. Once I have all my employees existing in the $employee array of arrays, I can refer to each employee by their respective attribute and their index. For example:

$employee['salary'][0]

is how I would refer to the variable that holds 58234.50 in memory. The name of my twentieth employee held in my $employee variable would be referred to as:

$employee['name'][19]

whereby the single quotes around the associative descriptor and the use of square brackets around both the associative and integer indices are strictly conventional (and yet used by many programming languages so if you can learn it once, you'll recognize it often). I can change this employee's name with an assignment:

$employee['name'][19] = "Lucius Monroe";

or like any String variable, I can print it out using any String printing feature of PHP:

echo $employee['name'][19];

These two examples of variable use would only be valid if a twentieth employee were defined in our code, or if we used a database to define the employees and only use PHP code to access the data (instead of having to do all the definition and management code in our PHP ourselves). Databases have huge advantages over using a specific programming language to generate and store data (we want to hide the details of that programming from our PHP-based Web pages.

Variables in Array Accesses

When using an numerical index to access data in an array, we often can use a variable to step through the data. For example, I might want to print out all my employee names:

<?php
$employee = array("ID"=>array("1217", "455"), "name"=>array("Bob Chen", "Lucy Jones"), "dept"=>array("Accounting", "Product Development"), "salary"=>array(58234.50, 87106.00));
$e_count = 0;
while ($employee['name'][$e_count] != "") { echo $employee['name'][$e_count]."<br/>"; $e_count++; } ?>

As we'll see below, we can use the $count() function to count the number of employees dynamically so we don't have to hard code a number into our loop (note I hard-coded the number 54 into the loop condition above). Or, we can use the foreach loop statement block to move through the employees without needing to reference the numerical index at all!

Arrays of arrays

$insured = array(array('m','f'), array('s','m'),array('s','n'));

is not a three-dimensional array. It is a two dimensional array with dimensions of three and two. The 'f' element can be referenced by $insured[0][1].

The 'm' element in the middle array can be referenced by $insured[1][1] since it is the first offset of the first offset array.

The 'n' element of the last array can be referenced by $insured[2][1].

You can tell the number of dimensions by how nested the array() function calls are. Just look at how deep the parentheses are nested. They are only nested two levels deep so of course this has to be a two-dimensional array.

You can start off with array(array()) to make sure you are only creating a two-dimensional array. Then, you can expand on the inner array to fill in all the detail as you want:

$gallery = array(array('1.jpg','2.jpg','3.jpg','4.jpg','5.jpg','6.jpg','7.jpg'),
array('8.jpg','9.jpg','10.jpg','11.jpg','12.jpg','13.jpg','14.jpg'),
array('15.jpg','16.jpg','17.jpg','18.jpg','19.jpg','20.jpg','21.jpg'))


To have a three-dimensional array, there would have to be an array(array(array))) calling sequence to generate the arrays in three-dimensions.

For Mary's case, we just have an array of three arrays. The $gallery[1][3] variable reference refers to the second row, fourth image filename, 11.jpg.

The Foreach loop

Let's re-write our employee name list printer with the use of a foreach() statement:

<?php
$employee = array("ID"=>array("1217", "455"), "name"=>array("Bob Chen", "Lucy Jones"), "dept"=>array("Accounting", "Product Development"), "salary"=>array(58234.50, 87106.00));
foreach ($employee['name'] as $name) {
    echo $name."<br/>";
}
?>

We get rid of both the counter and the index itself! This convention has made its way into all the programming languages over the last five years. It lets us write code more like we would think through some process in our minds if we were doing it ourselves: "Let's see. I want to make a list of my employees. Let me try and remember each employee's name and then write that name on a piece of paper." Hopefully, you find the foreach loop very intuitive. If not, perhaps you've studied too many programming languages. I actually found I had to unlearn my other learned intuitions before I found the foreach statement to be as straightforward as it was intended! This has happened a lot in my career of late, but it also means that people don't understand as much about computers because the languages are further and further removed from looking like the computer processes it and more like how we humans think about it naturally given the events of our lives before we meet a computer for the first time.

Introduction to Pre-Defined Functions

Pre-defined functions are functions that come with a programming language that you don't have to define because the language defines them for you. Some programming languages have no pre-defined functions and yet people bundle libraries of functions with the language that make them seem as if they were pre-defined. Basically, the important lesson to take with you is that all functions must be defined somewhere - whether you are privy to that definition or not. Pre-defining a function in a programming language is a big decision, but not one we have to worry about in this class. Instead, what we need to focus on is getting to know the pre-defined functions as they are the right ones to use instead of defining our own wherever possible. All functions have a few important rules associated with them all:
  • All functions have a proper name with strict syntactical rules provided by the language.
  • All functions are called with the use of parentheses that are placed outside of any parameter list the function allows.
  • All functions have a return value that is automatically passed back to the calling code for use in that code.
  • All functions have a defined signature that defines proper use in terms of data types that can be passed to the function and returned from the function.
  • Functions that allow more than one variable to be passed into the function have a parameter list with parameters separated by commas.
Functions are an incredible ally for designers of computer code. They can bundle computation into smaller routines in order to reuse that computation in solving multiple computational problems. Functions demonstrated their value over many years and spurred on the transition from procedural to object-oriented code design which is prominent today. Any good programmer who designs functions also publishes use guides to smartly packaged bundles of functions called libraries. These library guides have become very prominent on the Web today which has been a great boon for us coders. We can search the Internet to find any library we are interested in. Go ahead and type 'PHP pre-defined functions' into your favorite Web search engine. You'll notice the many pages that make reference of the pre-defined functions refer to hundreds of pre-defined functions in PHP. As an administrator of the server, I can also add as many of the PHP extensions to our PHP service and then those functions contained in the extensions behave just like pre-defined functions for us as well. Take a look at this extensive list of PHP extensions. The list reads like a techical list of popular PHP features - features that will mean more and more to you as you gain PHP experience. Keep this list as a list of interesting things to investigate in order to open up possible creative directions for you to head in the future. But, there are recognizable extensions already: the Calendar extension, for example, let's you access a built-in Calendar functions in order to deal with leap year days and variable number of days in a month.

PHP also has pre-defined variables, many of which we will use in our next lesson on interactive PHP forms. The two pre-defined concepts interrelate with each other since a function cannot use a variable unless it has been defined either. We mask variable definition a bit in PHP because PHP will define a variable when we use it for the first time automatically. Pre-defined variables usually have some specialized feature which then makes them popular for using with pre-defined functions that understand that unique feature.

The count() and substr() functions

So, let's apply the five function rules to two PHP pre-defined functions we will use a lot in our code.
  • Both count and substr are valid names for a function and so we call call them by their names when we wish to use them.
  • Both count() and substr() are called with the use of parentheses to tell PHP we intend to use the function and not something else called count or substr.
  • Both count() and substr() have return values: count() returns an integer that is a count of the number of items in an array and substr() returns a string which is a substring of the first parameter passed in.
  • Both count() and substr() have defined signatures:
    • count() requires that we pass in an array and only assign an integer-capable variable to its return value.
    • substr() requres that we pass in a string and an integer start character position and only assign a string-capable variable to its return value - but, in substr's case, we can also pass in an optional third variable: an integer length of characters that we want returned in the substring. The more flexible the function, the more likely we will be able to pass in a variable list of parameters.
  • count() only takes in one parameter while substr() takes two or three. When we use substr(), we must place a comma between each parameter in the parameter list.
We can use the count() pre-defined function to print a count of employees from our array discussion above:
echo count($employees);

We can use the substring() pre-defined function to print the first four letters of the first name of an employee:
echo substr($employee['name'][0], 0, 4);

Knowing these two functions are just two of hundreds of pre-defined functions we can use in our PHP code to do useful work let's us dive into the on-line libraries and explore functions that suggest creative uses for PHP.

In class, I showed you a bit of how to use arrays to manage the contents of an on-line directory for more interesting filtering techniques. That code has been cleaned up below. You can play with the array that is generated and even replace the processing code with it if you want. Otherwise, put your efforts into something more useful for you and await our database work for processing data with a database at your disposal. All the code has been commented where relevant.

Remember, in order to add a new line of data to the file, you need to pass the information into the PHP code via the Common Gateway Interface. We played with that syntax in class:

http://localhost:8888/writefile.php?town=Providence&uv=5.7&pollen=88

Our data.txt file

Richmond,85;8.1
Madison,82;6.4
Wichita,86;7.5

Our readfile.php file

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head><title>Example of Reading Data Files</title></head>
    <body>
	<?php
		$data = array();
		$row = 0;
		$infile = fopen("data.txt", "r") or exit("Unable to open file!");
		
		//Output data in the file until the end is reached
		echo "<table cellpadding='3'>";
		while(!feof($infile))
		{
			$next = fgets($infile);
			$town = substr($next,0,strpos($next,","));
			$pollen = substr($next,strpos($next,",")+1,strpos($next,";")-strpos($next,",")-1);
			$uv = substr($next,strpos($next,";")+1);
			$data[$row++] = array($town, $pollen, $uv);
			echo "<tr><td>".$town."</td><td bgcolor='yellow'>".$pollen."</td><td>".$uv."</td></tr>";
		}
		echo "</table>";

        ?>
    </body>
</html>

Our writefile.php file

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head><title>Example of Processing Data Files</title></head>
    <body>
	<?php
		$outfile = "data.txt";
		$data = array();
		$row = 0;
		$infile = fopen("data.txt", "r") or exit("Unable to open file!");
		
		//Output a line of the file until the end is reached
		while(!feof($infile))
		{
			$next = fgets($infile);
			echo $next."<br />";
			$town = substr($next,0,strpos($next,","));
			$pollen = substr($next,strpos($next,",")+1,strpos($next,";")-strpos($next,","));
			$uv = substr($next,strpos($next,";")+1);
			$data[$row++] = array($town, $pollen, $uv);
		}
		
		echo "<br />";
		
		//dump the array of data read
		var_dump($data);
		fclose($infile);
		
		$handle = fopen($outfile, 'a');
		if(isset($_GET['town'])) {
			fwrite($handle, "\n".$_GET['town'].",".$_GET['pollen'].";".$_GET['uv']);
			echo "<br /><br />I wrote: ".$_GET['town'].",".$_GET['pollen'].";".$_GET['uv']."\n";
		}
        ?>
    </body>
</html>
You can add a new record to the file through CGI (common gateway interface) processing via the URL:
http://localhost/week6/writefile.php?town=Norwalk&pollen=78&uv=6.5