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.
Rocket to Success - Your 10 Tips for Smarter ERP System Selection
Keep up with the latest tech news, reviews and previews by subscribing to the Good Gear Guide newsletter.

Gavin Sherry

PC World
Show Comments

Most Popular Reviews

Latest Articles

Resources

PCW Evaluation Team

Matthew Stivala

HP OfficeJet 250 Mobile Printer

The HP OfficeJet 250 Mobile Printer is a great device that fits perfectly into my fast paced and mobile lifestyle. My first impression of the printer itself was how incredibly compact and sleek the device was.

Armand Abogado

HP OfficeJet 250 Mobile Printer

Wireless printing from my iPhone was also a handy feature, the whole experience was quick and seamless with no setup requirements - accessed through the default iOS printing menu options.

Azadeh Williams

HP OfficeJet Pro 8730

A smarter way to print for busy small business owners, combining speedy printing with scanning and copying, making it easier to produce high quality documents and images at a touch of a button.

Andrew Grant

HP OfficeJet Pro 8730

I've had a multifunction printer in the office going on 10 years now. It was a neat bit of kit back in the day -- print, copy, scan, fax -- when printing over WiFi felt a bit like magic. It’s seen better days though and an upgrade’s well overdue. This HP OfficeJet Pro 8730 looks like it ticks all the same boxes: print, copy, scan, and fax. (Really? Does anyone fax anything any more? I guess it's good to know the facility’s there, just in case.) Printing over WiFi is more-or- less standard these days.

Ed Dawson

HP OfficeJet Pro 8730

As a freelance writer who is always on the go, I like my technology to be both efficient and effective so I can do my job well. The HP OfficeJet Pro 8730 Inkjet Printer ticks all the boxes in terms of form factor, performance and user interface.

Michael Hargreaves

Windows 10 for Business / Dell XPS 13

I’d happily recommend this touchscreen laptop and Windows 10 as a great way to get serious work done at a desk or on the road.

Featured Content

Latest Jobs

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?