A closer look at arrays in PHP

Over previous tutorials, we have occasionally made use of arrays without going into much detail about exactly what arrays should be used for, which kind of arrays are supported by PHP and the routines the language provides to simplify array usage.

Python vs. PHP: Choosing your next project's language

What are arrays?

Generally speaking, an array is a data set, containing one or more members. It is a useful data structure, in as much as it allows related information to be stored in a single variable. For example, say a PHP script has to manipulate information concerning a user's username, e-mail address, first name and last name. This information can be stored in four variables. But what if the script has to manipulate the data for 1000 users, in the same script? That would require 4000 variables! By storing all the user data in an array, such a script can be greatly simplified.

Arrays in PHP have another property: they are a dynamic data structure. That is, unlike an integer which can have a maximum value of 2147483647 in PHP, arrays can (theoretically) have an infinite number of members.

Arrays in PHP

Arrays can be created in several ways in PHP. For example:

01 <?
02 $a = array(1,2);
03 ?>

This creates an array with two members: 1 and 2. The following is equivalent.

01 <?
02 $a = array();
03 $a[] = 1;
04 $a[] = 2;
05 ?>

PHP also supports associative arrays. Such arrays allow developers to associate a unique name with any given member of an array. Consider the following:

01 <?
02 $a = array("username"=>"gavin","email"=>"gavin@my.host.com",
03		"firstname"=>"Gavin","lastname"=>"Sherry");
04 echo "Username: {$a["username"]}\n";
05 ?>

Lines 02 and 03 declare an associative array $a, containing information about a user. Keys, such as 'username' and 'email', are related to the values in the array, allowing data to be referenced by an associative name. Line 04 outputs the value of the username, referring to it in the array by name.

Notice that when a specific value in an array is referenced by the echo statement, it must be surrounded by curly brackets {}, otherwise PHP takes it to be a literal.

Basic array manipulation in PHP

PHP provides many functions to allow developers to get the most out of arrays. At their most basic level, these functions allow values to be added to arrays, removed from them and for the number of members in an array to be returned. Consider the following example.

01 <?
02 $a = array();
03 array_push($a,"apples");
04 array_push($a,"oranges","bananas");
05 while(list($key,$val) = each($a)) {
06     echo "key = $key, val = $val\n";
07 }
08 reset($a);
09 array_pop($a);
10 while(list($key,$val) = each($a)) {
11     echo "key = $key, val = $val\n";
12 }
13 ?>

This script creates an array, $a, on line 02. Three members are then added to the array: 'apples', 'oranges' and 'bananas'. To do this, the script 'pushes' new members on to the array $a. The term 'push' is used by PHP, since we are treating the array as a dynamic data structure, onto which we can stack more and more data. Notice on line 04 that two values are added by a single array_push() call. PHP interprets any arguments after the first to be new members for the specified array.

At line 05 , the script iterates through $a using the each() routine. The first call to each() returns an array consisting of the first member of $a and its key. In doing so, it increments an internal pointer, so that the next call returns the second member of $a, and so on. When all members have been returned, each() returns false, breaking the loop.

In conjunction with each(), the list() function is used. This is something of a quirk of the PHP syntax, but basically it allows developers to populate variables from an array returned by each() (or any other array returning function).

Line 06 outputs the data returned by each() to the user.

Line 08 resets the internal point of the array to the first item while line 09 'pops' the most recently pushed item off $a - this item is no longer a member of $a. The script then loops through $a again, proving that the popped item is no longer a member of the array.

Join the PC World newsletter!

Error: Please check your email address.

Struggling for Christmas presents this year? Check out our Christmas Gift Guide for some top tech suggestions and more.

Keep up with the latest tech news, reviews and previews by subscribing to the Good Gear Guide newsletter.

Gavin Sherry

PC World

Most Popular Reviews

Follow Us

Best Deals on GoodGearGuide

Shopping.com

Latest News Articles

Resources

GGG Evaluation Team

Kathy Cassidy

STYLISTIC Q702

First impression on unpacking the Q702 test unit was the solid feel and clean, minimalist styling.

Anthony Grifoni

STYLISTIC Q572

For work use, Microsoft Word and Excel programs pre-installed on the device are adequate for preparing short documents.

Steph Mundell

LIFEBOOK UH574

The Fujitsu LifeBook UH574 allowed for great mobility without being obnoxiously heavy or clunky. Its twelve hours of battery life did not disappoint.

Andrew Mitsi

STYLISTIC Q702

The screen was particularly good. It is bright and visible from most angles, however heat is an issue, particularly around the Windows button on the front, and on the back where the battery housing is located.

Simon Harriott

STYLISTIC Q702

My first impression after unboxing the Q702 is that it is a nice looking unit. Styling is somewhat minimalist but very effective. The tablet part, once detached, has a nice weight, and no buttons or switches are located in awkward or intrusive positions.

Latest Jobs

Shopping.com

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?