WordPress Development: Working with Arrays

If you’re creating variables to save values in your WordPress code, there may well come a time when it’s more efficient for you to use an array.

An array (or more specifically, an array of variables) lets you save multiple pieces of data using just one variable. It means you can save multiple records in the same way you might save multiple rows in a field, and then fetch each one by using the number in the array that it’s been stored against.

In this post I’ll explain what arrays are, why they’re useful and show you a couple of worked examples where they make the code more efficient.

So What is an Array and Why Would You Use One?

First let’s start by identifying exactly what an array is.

Wikipedia defines an array as:

“a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. An array is stored so that the position of each element can be computed from its index tuple by a mathematical formula. The simplest type of data structure is a linear array, also called one-dimensional array.”

This means that an array is essentially a list of values, all stored against one variable name. The values are listed in order and you can fetch each one by calling the variable with the corresponding number of that value (or element) within the array.

It may be easier if I show you what a simple array is by way of explanation.

A Simple Example of an Array

Let’s imagine you’re writing a plugin and you need to create a variable called $thing.

If your variable was a single static value, you’d create it like this:

But let’s say you want to add multiple values to your variable. You do this by creating an array:

Then to call one of the elements in your array, you use its number in the array, bearing in mind that you start with zero. So to fetch the ‘WordPress’ variable and assign it to another variable called $bestcms, you’d use this:

This tells you how to create a fairly simple array of variables and fetch elements from that array. Don’t forget that this requires you to know what order the elements are in, within the array.

Worked Examples in WordPress

That’s all well and good, but you might be wondering why it’s useful in WordPress.

I tend to use arrays of variables in WordPress when I’m creating some sort of loop, and then I want to access the data fetched by that loop when I’m outside it.

This gives you more flexibility to use data fetched by a query in whatever way you need to. Here I’m going to show you two examples – one using WP_Query and the other using a foreach loop.

Using Arrays with WP_Query

I used a technique like this in my post on creating a button to run and output a custom query.

Let’s take a look at that code.

This example uses a custom post type with a number of custom fields (or post metadata). The query fetches posts of that post type and their custom fields, which are then outputted outside the loop. The reason this is necessary is that fields from multiple posts are output together.

Here’s the query:

The query is then run, with a count function used to assign numbers to the data that’s fetched:

Let’s take a closer look at what that does:

  1. It starts the query and checks that it has fetched posts.
  2. It creates a variable called $currentpost and assigns it a value of zero.
  3. It runs the loop with three arrays: $favorite, $best and $worst, with each being assigned a value from a custom field. In each case the value is placed in the array at a position that uses the value of $currentpost.
  4. It adds one to the $currentpost variable.
  5. It ends the loop and resets postdata

When the loop runs a second time, variables will be stored in each array, but this time at position [1]. And when it runs a third time, they’ll be stored at position [2]. This means we now have three values stored in each array of variables: one for each post fetched by the query. And it means we have nine values in total: three for each of three arrays.

Storing the variables in arrays like this means we have access to them outside the loop. This code outputs one custom field from each of the three posts queried, using this line:

This gives us a single paragraph with custom fields from three separate posts.

Using Arrays with a foreach Loop

Let’s take a look at another example, not using WP_Query.

In this case we’ll use get_posts() with a foreach loop to loop through each of the posts. I’ll output the names of the three latest posts, in a single paragraph with links. This time we only need to use two arrays.

Here’s our get_posts() function:

This will fetch the latest three posts. Here’s the foreach loop with the two arrays:

This will fetch the title and permalink for each of the three latest posts and save them in our arrays.

Now here’s the code to output them together:

This will create a paragraph with the titles of the latest posts and a link to each.

Using Arrays will Broaden Your WordPress Horizons

Being able to store data in arrays will give you more flexibility when it comes to working with and outputting codes in WordPress. In the examples above I’ve shown you how to use arrays to store data from a loop (both using WP_Query and get_posts()) and then output that data outside a loop.

There are plenty more ways you could use arrays – let me know how you use them in the comments!

Rachel McCollin
Did you find this tutorial helpful? let me know how you are using arrays. We love your feedback. :)

3 Responses

  • Syntax Hero

    Thank you for this post.
    It covers arrays in a basic way, but it is clear and to-the-point.

    I am a bit surprised though, that you did not mention the fact that arrays are mainly used to save time on repetitive tasks.
    As far as I’m concerned, I use them to output data that follows a pattern a lot of time in a three-part way: define the data, define how one set is displayed, loop through the array.

    For instance, let’s say that you want to display user testimonials on your website.
    You could have a basic html structure that you would copy and paste each time you have a new testimonial to display.
    The problem is that each time you would need to get your hands in HTML again (and since this post is aiming at people who are not familiar with arrays, I guess messing with code is always a bit painful for them). Also, if you would like to change the way testimonials are displayed (let’s say switching from an to and , for instance), then you would have to change each separately.

    Here is when arrays come in handy.

    First, you define your array.
    For instance:
    $testimonials = array(
    ‘one’ => array( ‘name’ => ‘example’ , ‘testimonial’ => ‘This is a great post’),
    ‘two’ => array( ‘name’ => ‘homer’ , ‘testimonial’ => ‘duh’)

    This solves problem one: each time you have a new testimonial, there is only one row to add.

    Then, you create a display function. For instance:
    function display_testimonial( $testimonial ){
    return “$testimonial[‘name’]$testimonial[‘testimonial’]”;

    This solves problem number two : you can change the display for each instance in one quick tweak.

    Then, in your shortcode (or wherever), you can use a loop

    foreach( $testimonials as $t ) echo display_testimonial($t);

    Obviously, for a full post, you could make this code a bit nicer and safer.
    But I think it would have been great to explain a bit further how arrays truly are time savers!

  • Mr. LetsFixTheWorld

    Agreed that it’s a nice WP-focused intro, and Thanks. But even given the limits of a blog and a fallback to “we can’t explain absolutely everything”, I think this didn’t go near the point that it should as an introduction.

    I’m surprised that you actually used associative arrays (key-value pairs versus indexed) a couple times without mentioning them at all.

    Short/bracket syntax is extremely common in WP, not mentioned here. Same with $arr[]=”new_element”.

    And I think the finale for a piece like this should include references for further learning. That would at least include w3schools.com, page: php/php_arrays.asp, certainly php.net, page: manual/en/language.types.array.php, and ideally a teaser for another blog that actually does go further. I think all this needed was a summary like “stay tuned for part2 where we get into a few more common uses of arrays in WordPress”.

    You don’t need to provide a full education in a blog, it’s not expected. But if you’re going to introduce a topic, take it somewhere, or give the reader tools so that they can go further. I guess I’m saying, do this, or don’t. Otherwise, what’s the point? Um, thanks. :)

Comments are closed.