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 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

Cool Tech

SanDisk MicroSDXC™ for Nintendo® Switch™

Learn more >

Breitling Superocean Heritage Chronographe 44

Learn more >

Toys for Boys

Family Friendly

Panasonic 4K UHD Blu-Ray Player and Full HD Recorder with Netflix - UBT1GL-K

Learn more >

Stocking Stuffer

Razer DeathAdder Expert Ergonomic Gaming Mouse

Learn more >

Christmas Gift Guide

Click for more ›

Most Popular Reviews

Latest Articles

Resources

PCW Evaluation Team

Walid Mikhael

Brother QL-820NWB Professional Label Printer

It’s easy to set up, it’s compact and quiet when printing and to top if off, the print quality is excellent. This is hands down the best printer I’ve used for printing labels.

Ben Ramsden

Sharp PN-40TC1 Huddle Board

Brainstorming, innovation, problem solving, and negotiation have all become much more productive and valuable if people can easily collaborate in real time with minimal friction.

Sarah Ieroianni

Brother QL-820NWB Professional Label Printer

The print quality also does not disappoint, it’s clear, bold, doesn’t smudge and the text is perfectly sized.

Ratchada Dunn

Sharp PN-40TC1 Huddle Board

The Huddle Board’s built in program; Sharp Touch Viewing software allows us to easily manipulate and edit our documents (jpegs and PDFs) all at the same time on the dashboard.

George Khoury

Sharp PN-40TC1 Huddle Board

The biggest perks for me would be that it comes with easy to use and comprehensive programs that make the collaboration process a whole lot more intuitive and organic

David Coyle

Brother PocketJet PJ-773 A4 Portable Thermal Printer

I rate the printer as a 5 out of 5 stars as it has been able to fit seamlessly into my busy and mobile lifestyle.

Featured Content

Product Launch Showcase

Latest Jobs

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?