xmouse

Arrays in PHP

Arrays are one of the most useful tools available to the average programmer. Learning to program with advanced arrays is a skill everyone who touches a scripting/programming language should know about. As a quick case-in-point: this site (based on the WordPress CMS) uses arrays to a large extent; my /index.php page (which manages the display of any posts, eg the homepage, posts in 2004, post in category CSS) loops through an array $posts, displaying each post as either the full post or just an excerpt depending on what’s meant to be shown.

Starting simply

Arrays, simply put, are just a list of variables contained in one variable. Here’s a quick example of how we create an array:

Note the syntax there. I find it helps to read it out loud: “Weekdays is an array. Put in it the values Monday, Tuesday, Wednesday, Thursday and Friday”. The operator array creates a new array. Inside parenthesises (that’s brackets, ‘(’ and ‘)’) you put the values you want in the array, seperated by commas. I find it helpful to put the values on new lines, as it makes it easier to read (especially when the values are complicated). Don’t forget the semicolon afterward, as this is still a normal statement.

Now you’ve created an array, you need to know how to access the variables inside one. We do that with the square-bracket operator []. This appears just after an array variable’s name, and inside you put the index (the position of the value within the array) of the variable you want to retrieve. For example, $weekdays[3] would return the fourth (note: PHP starts counting at 0) variable in $weekdays, ‘Thursday’. Of course, you don’t have to have just a plain integer in between the brackets. You can perform operations that PHP will execute as well, for example $weekdays[count($weekdays) - 1] returns the last (remember the above note ;)) variable in $weekdays. Simple!

Associative arrays

Because average humans can’t be expected to remember the indexes of all their frequently-accessed variables, associative arrays were invented. This allows you to access a variable by a unique keyword. You define these keywords (normally just referred to as ‘keys’) when you’re defining the values in an array, like so:

The key is the bit before the => operator. You still use the square bracket operator to retrieve the values, but this time you use your set key between the brackets: $birthdays['me'] will return ‘19th March’. Again, the keys can be any simple variable, so just strings or numbers this time, no objects/arrays.

Keys and associative arrays are an invaluable part of array programming. They basically allow you to create term-definition pairs, or indeed anything else that is related, and generally just simplify array usage. It’s also interesting to note that all arrays are technically associative: if you don’t assign keys, PHP will automatically generate them for you (0 is the key for the first object, 1 for the second, etc.). It follows that you could create an array where the indexes run in any order, for example:

Here $backwards[0] will return the last value, not the first!

Multi-dimensional arrays

Remember when I said variables in arrays could be of any type, including other arrays? Well, creating an array like that is called a ‘multi-dimensional’ array. The syntax is self explanatory, really. Accessing is a little more complicated, but even that is fairly easy. Anyway, less talk, more code.

(Note: the above example is a more or less perfect application of objects, but we’ll leave that alone for now.) There you go, an array of arrays. But you needn’t stop there: if there’s a need, there’s no theoretical limit to the number of dimensions you can have in an array. So then, how to accessing these types of arrays is as I said a little more complicated, but still pretty easy to get your head round: $flowers[0]['size'] would return ‘up to 2m’. Of course, you could have an associative array at the top level as well, so you would access it something like $flowers['germanium']['size'].

Next in series

In a couple of days, I’ll be writing a follow-up to this piece, which explains how to loop through arrays and display their contents easily.