Web Developer's Virtual Library: Encyclopedia of Web Design Tutorials, Articles and Discussions


WDVL Newsletter

Active Server Pages
JSP/Java Servlets
Microsoft SQL Server
Daily Backup
Dedicated Servers
Streaming Audio/Video
24-hour Support    

jobs.webdeveloper.com

Hiermenus


e-commerce
Partner With Us















Developer Channel
FlashKit.com
JavaScript.com
JavaScriptSource
Developer Jobs
ScriptSearch
StreamingMediaWorld
Web Developer's Journal
Web Developer's Virtual Library
WebDeveloper.com
Webreference
Web Hosts
XMLfiles.com

internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Data collection: Arrays

July 21, 2000

Earlier we said that scalar values were just "one thing", or a single data point. Sometimes you need to contain a series or collection of "things". For example, suppose you want to keep a list of colors. A list, if you think about it, is really a collection of scalar values: "blue", "indigo", "yellow", and so on. Programmers call such a list an array, and PHP provides support for arrays.

Experienced programmers will note that in PHP, an array is both a list or indexed array and an associative array or hash table -- there aren't two different types of arrays. In this sense, all PHP arrays are really associative arrays but can be treated as indexed arrays where the indices are keys. If the previous sentence made no sense to you, don't worry about it, this is mostly important to those familiar with other languages' types of arrays.

Assigning a collection of values to an array variable is simple using the array() construct:

$colors = array("blue","indigo","yellow");

Or, if you know that you want to create an array $colors but don't yet know what values to fill it with, create an empty array:

$colors = array();

Adding new values to the array is a breeze:

$colors[] = "hunter green";

Now the array $colors contains four values. Often times, you need to access a single item in an array, such as for output or a calculation. To do this, you need to refer to a key, which leads to the value you want. We haven't created any keys ourselves in this example, and so PHP has created numeric keys: the key for the first item ("blue") is zero, the key for the second item is one, and so on, with the key for the last item in a list being the number of items minus 1, since keys begin at zero. So, we can output the second color in the array via the key 1:

print $colors[1];

...will output "indigo". This type of indexed key system is great when you want to keep items in a specific order, but it's also limiting because the keys don't really mean anything. How do we know we want the second key? In some applications we do know ... in others, this thinking just doesn't work. The alternative is to create keys which are meaningful labels. For instance, suppose our collection of colors was really a list of colors for our car. A car may have several colors, depending on the part of the car -- exterior, trim, fabric, dashboard. Here it makes sense to use keys which are labels more meaningful than a mere index:

$colors = array("exterior"=>"blue",
			"trim"=>"indigo",
			"fabric"=>"yellow",
			"dashboard"=>"hunter green");

Admittedly, this is one ugly car. Our list items have gained meaning but lost order -- which is fine, since this list is not about order. It's now easy to output the fabric color of this car, because "fabric" is a key in the list:

print $colors[fabric];

...will output "yellow".

Once you've built an array, you typically need to manipulate it somehow, such as to sort it or simply output each of its values. PHP contains a variety of functions for working with an array, most of which we won't cover here. Let's say, though, that we wanted to output each of the items in $colors, along with the key associated with that item. The general procedure for "stepping through" an array and processing each of its items will apply to many arrays you use in the future -- let's use this procedure on $colors.

while (list($key,$value) = each($colors)) {
	print "$key: $value<BR>";
	}

Although we haven't discussed the while loop yet, bear with us! The above code sets up a loop, or a series of repeating steps. The each() function returns a list (array) of values corresponding to the key and value for a single item in the array. These returned values are assigned on-the-fly to $key and $value, courtesy of the list() function. The print statement simply outputs the key and value for the current item in the list -- of course, you could do much more complex things with these values at this point in the code. Each time the loop returns to the while statement, it gets the next item in the array. When the array is completed the while loop will end.

In the browser, the above code would output:

exterior: blue
trim: indigo
fabric: yellow
dashboard: hunter green

Notice the order of our output, though -- same order that these items were defined earlier in our original array() statement. Suppose instead that we'd like to sort this array alphabetically by key, so that "dashboard" appears first and "trim" last. Simply, use PHP's ksort() function to sort $colors by key, and then step through the array as before:

ksort ($colors);
while (list($key,$value) = each($colors)) {
	print "$key: $value<BR>";
	} 
	

The PHP reference manual details a variety of additional functions for managing your data arrays and performing nifty acrobatics.

Scalar Variables and Data
Welcome to PHP
PHP Variables and Web Forms


Up to => Home / Authoring / Languages / PHP / Welcome




Jupiter Online Media: internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and Jupiter Online Media

Jupitermedia Corporate Info


Legal Notices, Licensing, & Permissions, Privacy Policy.

Web Hosting | Newsletters | Tech Jobs | Shopping | E-mail Offers