This article is an in-depth introduction to PHP arrays. We’ll cover what PHP arrays are, how to create and work with them, and a few less-known topics that even experienced PHP developers may find informative.

Going back to basics is a great way to make sure you’re on solid footing. This is especially useful for a topic as instrumental as arrays in PHP. You can get really far in WordPress development without fully understanding PHP arrays, but you’ll get almost nowhere if you don’t know the basics. We’ll start with the fundamentals of arrays in PHP, and then tackle more intricate topics.

What is a PHP Array?

At the most basic level, a PHP array is a list. If you’ve programmed before, you might have encountered a similarly-named thing (fancy word: “construct”) in most other programming languages. In JavaScript, and many other languages, an array is a simple list of values. Such a list will only have one-layer of meaning; and in PHP sometimes arrays are just lists of various items. So you might have an array of integers: [1, 2, 3, 4, 5] or of a mixed type [true, 1, 'red', 5, $object, 'marshmallow'] . Either of these list-like sets are valid PHP arrays.

Fred told me he likes to think of arrays as things like a shopping list. Expressed in PHP, my list from the other day would look like:

$to_buy = [ 'bananas', 'onion', 'chocolate' ];

An array containing a list of things can be pretty useful for programming. Let’s say that you want to iterate through your shopping list, searching the store for each item one-by-one. That’s the perfect use for this most basic form of PHP arrays. We’ll cover *how* to do that elsewhere, but the PHP data structure of an array is the perfect one to use for that.

Associative Arrays are Ordered Combinations of Pairs

What differentiates PHP arrays from those of other languages is that they aren’t exclusively a list-like data type we explained above. In PHP, there are slightly more structured (or “two-dimensional”) arrays as well. These are where we actually keep sets of “key-value” pairs. These are called “associative arrays” in PHP, because they let us “associate” something with our array’s main values. This allows us encode pretty meaningful information, like:

[ 'name' => 'David Hayes', 'age' => 33, 'race' => 'white', 'hair' => 'bald' ]

This information about your author isn’t the most interesting, nor the most useful example. But it clearly demonstrates what this “second dimension” of the array gives us: more context for the values it contains. The “values”-only array, ['David Hayes', 33, 'white', 'bald'] might be comprehensible. But maybe that 33 is his shoe size, or his femur length. This is why we often prefer to use associative arrays, rather than simpler “one-dimensional” arrays in PHP and WordPress development.

Even Non-Indexed Arrays Have Indexes

Another thing that’s not totally clear, but true is that even if you make an array that’s just a list of things, internally PHP still makes it into a key-value paired-set. So ['bananas', 'onion', 'chocolate'] is actually an identical array to one declared as:

[ 0 => 'bananas', 1 => 'onion', 2 => 'chocolate' ]

Admittedly this second version is more verbose, but it’s what actually happens. This highlights another important things: “indexes” or “keys” in PHP—and most other programming languages—start at 0 rather than 1. This is for good reasons, although it can be confusing at first. But “zero-indexing” is the reason that the banana are the “zero-ith” element of the array, and not the “first” one. Even if you’ve programmed for years, this may still surprise you from time-to-time.

Getting a Little Nerdier: Arrays are Ordered Maps

Because all PHP arrays are actually associative, they’re super powerful. Most other languages don’t call this “key-value pairs” structure “arrays.” In Python they’re called “dictionaries”, in Java they’re “hash tables”, in JavaScript you make “objects” for this sort of behavior.

This ability to arbitrarily have named keys is one of the best and worst things about PHP arrays. Mostly it makes them the most-used data type in the language, especially for WordPress developers. The PHP documentation has some true but not-super-clear language about arrays. It says:

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Now that you’ve read my previous section, I hope you can kind of understand what PHP.net is saying. Essentially, PHP arrays can be (and are) used for lots of more-esoteric kind of data usage than simple lists. This is because they can become key-value correlating “dictionaries”. This whole set of varied behavior of arrays in PHP has historically had a bit of performance cost, but especially in PHP 7 the cost has shrunk significantly.

All the Ways to Declare Arrays

The astute among you may have noticed that so far I’ve been exclusively referring to PHP arrays with what is sometimes called a “short” array syntax—square brackets: [] . Before PHP 5.4, you had to declare an array by using the array() function (technically a language construct, but the difference is way beyond a sane scope for this article). So you’d declare a list with the values of 1, 2, and 3, like this:

array(1, 2, 3)

Functionally, this syntax and the square-bracket one [1, 2, 3] are identical… as long as you’re running on a server that’s using PHP 5.4 or above. If this tutorial were not for a WordPress-focused site, this wouldn’t matter at all. But it’s still the case that lots of WordPress code has remnant of its history running PHP down to 5.2. In WordPress 5.2, the project stopped officially supporting PHP 5.2. (One of those nice memory-aids.) So this is now, thankfully, mostly something you should know and understand for reading older code.

Adding Values to Declared Arrays

The other nice quality of the shorter array syntax is it matches lots of other ways you’ve been able to work with PHP arrays for a while. Let say you want to add a value (or key-value pair to an array), my favorite way to do that has always been:

// add it with the next numeric key: $num_array[] = 91; // add it with a specific key: $array['new_key'] = 'new_value';

For the first form, you can also use array_push($num_array, 91) . The second has never had a different way to accomplish it. So square brackets have been related to arrays in PHP for quite some time.

You’ll often add values to already-declare arrays in PHP, for reasons of logic of the code you’re writing. Arrays are kind of the universal data holders in PHP, so you do that sort of thing with them a lot.

The ease of declaration, reading, and manipulating arrays is the big reason that you’ll so often see $args arrays in WordPress PHP. And, unlike object or functions, it’s possible to skip declaring arguments or properties, if the code that’s receiving is built correctly. (The internals of WordPress are.) I won’t go into a lot of details, because Fred already wrote a great article on the topic of $args arrays:

Reading Values from PHP Arrays

If you’ve got a PHP array that already exists, and you want to know the value at a specific key, you’ll typically do that with:

$val = $numeric_indexed_array[3]; $var = $word_keyed['lookup'];

None of this will suprise you, if you’ve started to feel comfortable with the square-bracket syntax. The key thing to see is that the “key” goes in the square brackets, and that key can either be a number or a string.

One other common-enough-case of data access in arrays is where you want the first element in an array that may not be zero-indexed. (That is, the first pair in the array may be something like 27 => 'elephant' .) If you have an array that doesn’t have reliable keys, the way to get its first elements is the array_shift PHP function.

Similarly, if you want the last element but don’t know the index of that element, you can use array_pop . (If you’re familiar with programming and have heard of a “stack”, this is where you commonly hear of push—mentioned in the last section—and pop as opposites.)

The Important and Magical $_GET and $_POST Arrays

It may go without saying, but $_GET is for query string elements, $_POST is for values HTTP POSTed to a page.

Probably the most common place that a PHP developer must read values from arrays is the $_GET and $_POST superglobals. Going into exhaustive detail on these is beyond the scope of this article, but they are how you access the query string values that someone has added to a URL, http://example.com/?id=102932 , or access the values “posted” via a from. ( $_GET is for query string elements at the end of a URL, $_POST is for values HTTP POSTed to a page most often when someone fills out a web-form.)

Both of these are simple PHP arrays, and people other than you (this can happen kind-of-commonly on a WordPress site) can have changed them before your code runs, or you might need to alter them to affect how other code runs. For better or worse, PHP just treats them as arrays that anyone can edit like almost any other array. So you read from them just like the arrays above, so $postid = $_GET['id'] . This also is how people write to them, but this in an introduction and I don’t encourage beginners to do that.

Finally there is also a $_REQUEST superglobal, which has essentially combined the $_GET and $_POST (and the $_COOKIES superglobal that I’ve personally rarely had cause to use) into a single array. Again, I’d discourage you from using it because it’s less clear about what’s going on, and thus a little less secure. But you may see code that accesses it, and it’s good to know what that’s about.

Looping Through Arrays

It is very common when processing lists (or associative arrays) that you want to iterate through them and do something with each element. Whether that is transform them, sum them, or display each element. Displaying each element of an array is actually the entire thing that WordPress’s infamous “loop” does. It’s a loop iterating through an array of WP_Post objects. For those totally unsure of what PHP objects are, the short version is that they’re more complex and structured data-and-functionality containers than arrays. More is explained here.

“The Loop” is mostly done using a while loop. (And, to avoiding making it too muddled, does technically rely on some functions and an object.) The most common way arrays are iterated through in PHP, by far, is foreach . It looks like this:

foreach ($array as $key => $value) { echo "Key is $key."; echo "Value is $value."; }

What’s great about foreach is that you can read it pretty easily like English. I’d read the above as “for each element in the $array array, use the keys as the $key variable, and the values as the $value variable. Use one pair for each iteration of the following code (contained in curly-braces).”

You can iterate using a for loop as well, but foreach is so much more common in PHP because is does pretty much exactly what you expect, and is much simpler to write. And one note—if you don’t need the array keys, this works the same: foreach ($array as $value) .

Going Beyond Looping

Loops are great, and very common for many different types of iterating through arrays that you might want to do. Because loops work in so many languages, they’re still most people’s preferred way to transform an array of things into a different array of things. But there is a better way: PHP has some functions that are made to let you transform all the elements of an array without using foreach .

Using these functions can give you cleaner code and make everything clearer. But they have a bit of conceptual complexity that is greater for most people starting out. Whether or not these “functional programming” concepts are right for you is a matter of personal choice. But you should definitely consider learning them if most of the rest of this article has felt like review to you.

Here’s the best introduction I’ve written about why and how you should consider array_map and array_filter :

Why Arrays Instead of Objects?

One of the more common questions that comes up is the difference between arrays and objects in PHP. Both are conceptual units that can hold lots of related data. So what’s the difference?

As I see it, arrays are great for quickly making un- or semi-structured sets of data. That’s why, as we mentioned earlier, $args arrays are really common in WordPress.

But sometimes you either want a more rigidly defined structure, or you want to have more “behavior” or functions related to that data structure. That’s where and when you should reach for a PHP object. Because object properties are more rigid than a random array, you can more reliably access properties of objects than indexes of arrays. So I’d feel much more confident that PHP won’t yell at me if I have an array of WordPress posts when I access the post objects as $post->title than accessing post arrays as $post['title'] . (Admittedly not a great example, because I trust WordPress in either case. :p)

Esoterica: Array-Access of Objects

Another less common thing about PHP object and arrays that you’ll sometimes see is this: in contexts it is possible to read a PHP object as an array. So if an object has a property $obj->length = 7 , sometimes you’ll see code successfully call $obj['length'] and get 7. How?

There are two ways. The less common one is that there is a PHP interface, ArrayAccess and if a class implements it, that object’s data can be accessed as an array. Personally, I’d not use this and wouldn’t implement it (outside of compatibility cases), but it’s confused me before so I wanted to mention it.

Another thing I’d not recommend but have encountered somewhat frequently: PHP objects can be coerced into arrays. How?

$array = (array) $object;

I’ve seen a newbie or two copy this sort of code because they don’t quite understand the underlying concepts and found this tip somewhere. Here’s what PHP.net says about this:

If an object is converted to an array, the result is an array whose elements are the object’s properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a ‘*’ prepended to the variable name. These prepended values have null bytes on either side.

The above is unlikely to matter to you most of the time, so don’t sweat not fully understanding it. The core thing to know is that you can access an object’s public properties as an array either by its implementing the ArrayAccess interface, or by someone casting it to an array. It’s not common, but it happens.

Related Reading on Arrays for WordPress

There are a few other piece of reading here at WPShout that build up from the concepts in this article that I wanted to point out. Here they are:

What We Learned About PHP Arrays

I hope now you know that there are effectively two types of PHP arrays: key-value pairs and simple lists. Both are called arrays in PHP, which is why an array is one of the most common types you’ll encounter in PHP, especially WordPress PHP. There are also a variety of ways to read from, add data to, and otherwise manipulate arrays. I hope all this will come in handy as you continue working on and learning WordPress!

Image credit: Wikimedia