Understanding the Basics of Arrays with PHP


Arrays are a pretty important concept in programming, but they’re something I went an embarrassingly long time not fully understanding when I first started learning. I recall spending far too much time in my earlier days trying to solve complex problems in convoluted and stupid ways. Most of these solutions could have just made use of an array and iterator if I’d only understood the concepts and their power. So if you have any interest in programming and aren’t 100% sure what an array is or how it works, let me save you some of that hassle.

What’s an Array?

In its simplest understanding, an array is a fancy programming word for a list. Just as a list can hold items, say for shopping, so can an array. We’ll use PHP here:

$shopping_list = array("eggs", "flour", "apples", "butter");

As you can guess, the variable '$shopping_list' — in PHP all variables start with a dollar sign — is now a list of four items I need to buy at the grocery store. However, there’s more to this than you might first expect.

For one, it’s worth noting that every value in an array has an “index”. The index of the array — when it’s not explicitly defined — is just the order to which the elements are added to the array. And because this is programming we start at zero, then we count up. So to know the third thing on my shopping list, I can find it with $shopping _list[2]. The square brackets are just away we identify subelements of an array, in this case I’ll discover that I need apples. Remember numbers for arrays start at zero.

Associative Arrays

An associative array, in common use, is one in which the indexes or keys are set explicitly to non-numeric values. This is the real start of the power of arrays. We can start to understand it by extending the shopping list example. The following expression creates an associative array:

$assoc_shopping_list = array(
    "eggs" => false, 
    "flour" => true, 
    "apples" => true, 
    "butter" => false
);

As you’ll notice, the same elements are in this list. The difference is that now the basic ingredients are the “keys” or indexes, and the values are whether or not I actually need the items on this trip. The job of the => is to assign a value to a key. In this case our associative array is telling me that I should only buy flour and apples. The doctor told me to watch my fat intake.

As we said before, if an array element is set without a corresponding key, it’ll be found at a numeric index. But when set with a corresponding key, we can get values based on the key. So the value of $assoc_shopping_list['eggs'] is false.

Going Further

Because of the ways in which arrays are different than standard lists, you can do a lot of powerful thing with them, and they’re used all over in programming.

One thing you may not know is that when you submit a form to a PHP webpage, it always accesses those values as an array. If you type in an search box, the resulting page will likely begin to work with your submission by finding the value at something like $_POST['search']. (The index of such requests is the same as the field’s name in HTML, and $_POST is an automatic PHP “superglobal” variable. If neither of those make a lick of sense to you, don’t worry.)

Similarly, you can programmatically read through an array and use the results. In this very basic example, we’re going to read through my associative array example and use it to make a basic list like the first example. Please also realize that if a real program were assigned this basic goal, there are other (better) ways to accomplish it. This example is just using the most universal and important-to-understand methods of arrays.

foreach ($assoc_shopping_list as $key => $value) {
	if ($value === true) {
		$assembled_shopping_list[] = $key;
	}
}

This is a lot of programming to hit you with, but I’m sure we can get through it. First thing to understand: curly braces surround the actions which result from the earlier declaration.

foreach is an iterator. It takes something like an array, and programmatically moves through it doing the action inside its curly braces. To explain the top line in English, we’re saying “For each pair in this array $assoc_shopping_list do the following action with the key of that pair set to the value of the variable $key and the value set to the variable $value.” To give complete clarity, what this means is that first time that we step into the curly braces, it will be with two variables set: $key will have the value eggs, and $value will have the value false. (Also worth knowing: you can use variable names other than $key and $value, I’m just using them here to drive that vocabulary home. If the variables were instead $item and $needed the logic that follows would be easier to comprehend.)

Having set our variables, we are now are at the if, and I won’t waste your time putting the sentence into English. But we find that the value of $value is false, and not true, so for this iteration (go-round) we skip what’s inside the curly braces after the if.  (In PHP, === checks strict equivalence (identical) because == checks “loose” equivalence (equal), and = is used to set variables.)

Now we’re iterating again, but this time $key will have the value flour, and $value will have the value true. As you know, true === true, so we’re inside the curly braces this time. In there, we’re doing something that can look a bit confusing. Essentially we’re assigning $key to a value in the array $assembled_shopping_list; the empty square brakets — [] — are a common shorthand for that action. (The more verbose version, which is less common, would be array_push($assembled_shopping_list, $key).)

On the next time around 'apples' will become the next value on $assembled_shopping_list. Finally 'butter' won’t be captured, and we’ve reached the end of our program. Now to find the first value in our assembled shopping list we can just type $assembled_shopping_list[0] and we’re buying flour.

And Finally

We’ve barely scratched the surface of all the things that programmers use arrays for. We’ve not talked about multi-dimensional arrays (when a value in an array is itself an array), or all the cool array functions PHP offers. But I hope you not have the basic understanding I initially lacked of this important programming concept.

About David Hayes

David likes learning, solving hard problems, and teaching. He bikes a lot, and lives in (and loves) Colorado. You can find him on Twitter as @davidbhayes and check out his latest hobby-project, Quodid, a monument to his love for pithy bits of wisdom.

3 thoughts on “Understanding the Basics of Arrays with PHP

  1. Pingback: Making Your First Shortcode Plugin in WordPress | Press Up

  2. Pingback: Getting to Know WP_Query | WPShout.com

  3. Pingback: Course: Working with WP_Query | WPShout

Leave a Reply

Your email address will not be published.