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.

Our Back to Business guide highlights the best products for you to boost your productivity at home, on the road, at the office, or in the classroom.

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

Gavin Sherry

PC World
Show Comments

Essentials

Microsoft L5V-00027 Sculpt Ergonomic Keyboard Desktop

Learn more >

Lexar® JumpDrive® S57 USB 3.0 flash drive

Learn more >

Mobile

Lexar® JumpDrive® S45 USB 3.0 flash drive 

Learn more >

Exec

Lexar® JumpDrive® C20c USB Type-C flash drive 

Learn more >

HD Pan/Tilt Wi-Fi Camera with Night Vision NC450

Learn more >

Lexar® Professional 1800x microSDHC™/microSDXC™ UHS-II cards 

Learn more >

Audio-Technica ATH-ANC70 Noise Cancelling Headphones

Learn more >

Budget

Back To Business Guide

Click for more ›

Most Popular Reviews

Latest News Articles

Resources

PCW Evaluation Team

Michael Hargreaves

Windows 10 for Business / Dell XPS

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.

Aysha Strobbe

Windows 10 / HP Spectre

Ultimately, I think the Windows 10 environment is excellent for me as it caters for so many different uses. The inclusion of the Xbox app is also great for when you need some downtime too!

Mark Escubio

Windows 10 / Lenovo Yoga

For me, the Xbox Play Anywhere is a great new feature as it allows you to play your current Xbox games with higher resolutions and better graphics without forking out extra cash for another copy. Although available titles are still scarce, but I’m sure it will grow in time.

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.

Featured Content

Latest Jobs

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?