A closer look at arrays in PHP

A closer look at arrays: Part II

The prvious page defined what arrays are, how they can be used in PHP and the elementary routines available in PHP to manipulate them. This time we will look at more advanced usage, including a number of support functions that provide sophisticated array usage, as well as methods of sorting arrays.

Advanced array usage

PHP has a large range of useful functions which can manipulate arrays. Some of the most widely-used ones are presented here. array_merge() can be used to join two or more arrays together. For example:

01 <?
02 $a = array(1,2);
03 $b = array(3,4);
04 $c = array_merge($a,$b);
05 ?>

Array $c on line 04 consists of the members of $a and $b, that is, 1, 2, 3 and 4. Any number of arguments can be passed to array_merge(). array_unique() is used to remove duplicate values from an array. Consider the following:

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

The array $b created on line 03 is a unique set of members from $a, i.e., 1, 2 and 3. It is often the case that a PHP script needs to check if a value is in an array. A developer could iterate through the array, checking each value, but the following is much simpler:

01 <?
02 $a = array(1,2,3,4);
03 if(in_array(1,$a)) {
04 echo "Value is in array\n";
05 }
06 ?>

The in_array() function tests whether the value passed as the first argument is in the array passed as the second argument. It is also useful to be able to retrieve a random value from an array. This can be done with the array_rand() routine.

01 <?
02 $a = array(1,2,3,4,5);
03 srand((double) microtime() * 10000000);
04 $key = array_rand($a,1);
05 echo "Random value = {$a[$key]}\n";
06 ?>

On line 03, the script seeds the random number generator. This is important in randomising the number used by array_rand(). The seed the script generates is based on the number of microns since the last whole second. For more discussion on this point, see: www.php.net/manual/en/function.srand.php.

On line 04, array_rand() returns a random key from $a. The second argument to array_rand() tells the routine to return only one random key. On line 05, the script retrieves a random value using the random key. The function shuffle() can be used to randomise the whole array.

Sorting an array

It is often important to sort arrays. Sorting a basic single dimensional array is simple.

01 <?
02 $a = range(1,20);
03 srand((double)microtime() * 1000000);
04 shuffle($a);
05 sort($a);
06 ?>

On line 02, the script defines an array whose members range from 1 to 20 - that is, 1, 2, 3, etc. The script randomises the array on lines 03 and 04. The array is then resorted on line 05.

Things get more complicated when you consider multi-dimensional arrays, but PHP has several functions to help developers with this. Consider the following:

01 <?
02 function cmp($a,$b)
03 {
04 $at = strtotime($a["date"]);
05 $bt = strtotime($b["date"]);
06 if($at == $bt)
07 return(0);
08 if($at > $bt)
09 return(1);
10 else
11 return(-1);
12 }
14 $a = array(array("title"=>"Title 1","date"=>" June 11 2003"),
15 array("title"=>"Title 2","date"=>"May 30 2003"),
16 array("title"=>"Title 3","date"=>"July 1 2003"));
18 usort($a,"cmp");
19 ?>

The script sorts the array $a according to the date field in each secondary array. To do this, the script declares a user-defined comparison function on line 02. This function receives two arguments, $a and $b. Each is an array from $a defined on line 14. In order to simplify sorting, the script defines $at and $bt, the UNIX timestamp representation of the dates defined in $a and $b, respectively. If these values are equal, cmp() returns 0. If $at is greater than $bt, the script returns 1; otherwise, -1.

With this defined, it is as simple as passing the multi-dimensional array the name of the comparison function to usort() on line 18 - PHP takes care of the rest.

There are many more array functions and many other ways to use arrays in PHP. For more information and examples, be sure to visit www.php.net/manual/en/ref.array.php.

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


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?