Absolute Beginners Guide to PHP Arrays

| Coding Tutorials

Arrays are wonderful ways to organize and use data in PHP.

Quite simply, an array is a list.

Here’s a quick example of an array of types of transportation:

$transportation = array( ‘Planes’, ‘Trains’, ‘Automobiles’ );

For readability you can write it like this as well:

$transportation = array(

    ‘Planes’,

    ‘Trains’,

    ‘Automobiles’

);

Now $transportation holds a nice little list of types of transportation. But what do we do with it?

Printing Array Items

Each of the visible items in the list above is called a value. Each value also has a key. If you don’t give an item a key, PHP will assign one, and it’ll be a number. Here’s a better visualization of what’s going on:

$transportation = array(

    0 => ‘Planes’,

    1 => ‘Trains’,

    2 => ‘Automobiles’

);

The => are assignment operators, and the numbers are the keys. Note that we started with 0. If you’re really assigning them yourself, you can start with 1, but I don’t recommend it, since the automatic system starts with 0.

To print the first element in the array you would do something like this:

<?php echo $transportation[0]; ?>

See the key there in the square brackets?  This code would output "Planes".

Custom Array Keys

You can also make up your own keys if you wish to. Here’s an example:

$web_site = array(

    ‘Name’ => ‘OSTraining’,

    ‘URL’ => ‘http://ostraining.com’,

    ‘Purpose’ => ‘Education’

);

And now you could do something like this:

<ul>

<li>Name: <?php echo $web_site[‘Name’]; ?></li>

<li>URL: <?php echo $web_site[‘URL’]; ?></li>

<li>Purpose: <?php echo $web_site[‘Purpose’]; ?></li>

</ul>

And you’ll end up with something like this:

Using custom keys can make it much easier to know what it is you’re printing simply by looking at it.

Loops

What if you don’t know how many items are in the array, or what the keys are?  PHP has a wonderful process called foreach. Using the $web_site array from above, here’s how it works:

<ul>

<?php

    foreach( $web_site as $key => $value ) {

        echo ‘<li>’ . $key . ‘:’. $value . ‘</li>’;

    }

?>

</ul>

Here’s what that’s doing in plain English:

For each item in the array, assign the variable $key for the key of each item, and $value for the value of each item. Then go through every one of them and print them out, stopping when we don’t have any more.

This code would produce the exact same bulleted list as the one I manually made above.

Foreach makes it very easy to take every array item and do something with it.

Multidimensional Arrays

A multidimensional array is one where the items in an array are themselves arrays. Here’s an example:

$staff = array(

    0 => array(

        [‘Name’] => ‘Topher’,

        [‘Position’] => ‘Standing or sitting, when not lying down’

    ),

    1 => array(

        [‘Name’] => ‘Steve’,

        [‘Position’] => ‘Writer’

    )

);

There we have a $staff array with multiple people in it. We could do multiple foreach functions to iterate over each of those people like this:

foreach( $staff as $key => $person ) {

    echo ‘<ul>’;

        foreach( $person as $attribute => $value ) {

            echo ‘<li>’ . $attribute . ‘:’ . $value . ‘</li>’;

        }

    echo ‘</ul>’;

}

In the above example I looped through each person, and within each person I looped through their attributes and printed them. You can make up whatever variable names you wish, there’s nothing magic about the names. I tried to name mine in a way that made sense according to the contents.

Putting It All Together

Arrays holding actual content are rarely handmade like the ones I’ve made in this post. Typically they come to you from a request of something, whether it be a database call, a REST request from a web API or whatever.

In the case of WordPress it’s very common to do a database call with WP_Query and get back a multidimensional array of Blog Post data. At that point you can use foreach to loop through those posts and print them.

The same will hold true of just about any CMS. If you’re making anything custom at all you’re probably making a database call and getting an array of data back.

Going Beyond

There’s much much more that can be done with arrays, far more than can fit into one post. They can be sorted, spliced, compared, counted, and twisted in all sorts of ways. I strongly recommend you read the documentation on the PHP web site. Most of the array functions are logically named, so you can tell what they do by the name. Once you get used to most of them you can do just about anything with arrays.

Bonus Functions

Here are some examples of some easy useful things you can do with arrays:

<?php $items_num = count( $array ); ?>

Assuming $array actually is an array, it’ll count how many items are in it, so you can do things like “14 search items found” (link)

<?php $array = sort( $array ); ?>

This will take an array, sort it from low to high, and assign it back to the same variable name. There are options to sort it numerically, or by string, or whatever (link)

<?php if( is_array( $array ) ) {

This tests to see if your variable is an array or not (link). It can be useful to cast a variable as something else early in your code, like this:

$array = ‘’;

And then change it to an array when the time is right. With this process you can know whether you’ve gotten your content yet or not.

Wrapping Up

As you can see, arrays can be incredibly flexible and powerful. They’re a wonderful tool for organizing and managing data, and allowing you to use that data in just about any way you can think of.


About the author

Topher is an accomplished programmer, having written his own content management systems and managed some very large websites. He loves to help people and believes playing with WordPress is fun. Topher lives in Michigan, USA.