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


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?