More PHP: Understanding Arrays

In our earlier PHP lesson we learned about variables. While variables are very useful for holding a single piece of data, there is a more effective solution for holding multiple related data elements: Arrays. So what are arrays? Think of arrays as sort of a "super variable" that can be used to store and extract vast amounts of information. Let's explore by revisiting our old friend variables.

Variables Again

Let's start our exploration of arrays with a refresher on variables.

1. Visit free.mynmi.net and download arrays.zip.

2. Unzip arrays.zip and upload the folder to your server.

3. From cyberduck, open the file called 1_variables.php with Brackets and look at the code. Inside of the php tags you should see a variable called $myname that is set to my (the author's) name and, immediately below, a line that says echo $myname;.

4. Substitute your name for Emuel, save the file and refresh it in your browser. Your name should appear.

As you probably have figured out, the variable $myname is set to the value of whatever your name is, and the echo statement tells the variable to display $myname. That's pretty much what variables do. They hold either string (as in names, phrases, etc.) or numeric data. The variable can be referenced to do something with the data such as displaying it, adding it to something else, etc. But what if you want to store several names at once. If you used variables you would have to come up with a cumbersome scheme such as $name1= "john"; $name2="Mary"; $name3="William"; etc. A much cleaner and easier way is to use an array; especially a basic kind of array which is known as a numeric array.

Numeric Arrays

Open the file named 2_basic_numeric_array.php and look at the code. Between the PHP tags you should see a line that states: $candidate= Array(); This statement creates an array named $candidate.

Now look at the subsequent lines that present presidential candidates from 2012 such as $candidate[0]="Mitt Romney"; $candidate[1]="Rick Santorum"; etc. The numbers that are associated with these lines 0,1,2,3,4 are used to reference the data.

Look further down to line 30 that states

echo $candidate[3];

Preview the file in your browser (your_domain_name/arrays/2_basic_numeric_array.php and the name Ron Paul should appear because he is the candidate referenced by the number 3. Change the number in the brackets to 4 as in

echo $candidate[4];

and Barack Obama will appear. Change 4 to 0 and Mitt Romney appears, etc.

Well that was simple (I hope). Now open 3_basic_numeric_array.php and look at its source code. This file shows the same $candidate array but this time one of the data points is tied to a variable named

$thecandidate as in $thecandidate=$candidate[4];

The next line echoes $thecandidate rather than specifically echoing $candidate[4] from the array but the outcome is the same.

Pulling data sequentially from an array

OK, it's about to get more exciting. Open 4_basic_numeric_array.php and take a peek at lines 30 through 32 as shown at right. This statement uses the foreach command to loop through the entire array and output the name of each candidate. On line 30 each component of the $candidate array is set to a variable named $whichone. Line 31 echoes a line break to separate values. Line 32 displays the actual variable on the screen, beginning with $candidate[0], Mitt Romney and ending with $candidate[4], Barack Obama. Browse to 4_basic_numeric_array.php to see the result.

Open yet another file called alternative_numeric_array.php with Brackets. This time viewing the file with your browser produces exactly the same result as the previous file, even though the array is set up differently.

$candidates=Array('Mitt Romney','Rick Santorum','Newt Gingrich','Ron Paul','Barack Obama') 

instead of something like

$candidate[0]="Mitt Romney"; $candidate[1]="Rick Santorum";

In both cases the function of the array is identical and it is a matter of personal preference as to which method you use. The first method of creating an array seems easier, but the second method (perhaps) presents the data more clearly.

Associative Arrays

Now that we have looked at numeric arrays it is time to visit another type known as associative arrays. Unlike numeric arrays which are indexed by numbers, associative arrays are indexed by by string variables such as names. Open 5_associative_array.php and take a look at the state array that presents each candidate's home state, indexed by their last names. As you see, the statement for outputting Obama's state to the browser is echo $state ['Obama'] instead of echo $state [4]. Substitute one of the other candidates for Obama and watch the display change. Almost too easy right? 

$state=array(
'Romney'=>'Massachusetts',
'Santorum'=>'Pennsylvania',
'Paul'=>'Texas',
'Obama'=>'Illinois');

//pull the data one piece at a time

echo $state['Obama'};

Now open 6_associative_array.php, look at lines 30 - 32, and test the file in live view. Once again the foreach statement is used to output all of the data in the array in the same way that it is used to output data from a numeric array. 

Multi-dimensional Arrays

Multi-dimensional arrays are used to store data that is more complex. The most useful and daunting characteristic of multi-dimensional arrays is that they are made up or arrays inside of arrays. Or arrays inside of arrays inside of arrays inside of arrays. You get the idea; they can be complicated.

Open 7_multidimensional_array.php and look at the array named $details, starting on line 25.

romney As you can see $details starts with the candidates' names which in turn lead to a series of associative arrays that contain information about each candidate's state, religion, year of birth, and the name of their spouse. At first glance this type of array can appear confusing but that's nothing compared to encountering this type of array when you are teasing data from the Facebook graph for example, because you can't even SEE all of the data or the embedded associative arrays. What do you do?  One word: var_dump.

Your friend var_dump

To see how var_dump works look at line 57 which asks for a var_dump of the entire $details array. Now click Live View to see what var_dump does. Confusing? Let's look at Romney's data and see if we can de-mystify this stuff a bit:

["Romney"]=> array(4) { ["state"]=> string(8) "Michigan" ["religion"]=> string(6) "Mormon" ["year_born"]=> string(4) "1947" ["spouse"]=> string(10) "Ann Romney" }

The initial statement ["Romney"]=> array(4) is trying to tell you that there are 4 separate data points associated with Romney: state, religion, year_born, and spouse. The statement ["state"]=> string(8) "Michigan" is telling you that state is an 8 character string variable which is, of course, Michigan. The same pattern applies for all of the other data; for example spouse is a 10 character string: Ann Romney.

So how do you get beyond the confusion of var_dump to discrete data that we can actually use? Let's start by commenting out the var_dump statement by placing two forward slashes in front as in:

//var_dump ($details);

Next, remove the slashes from //echo ($details), save the file and live view it again. Oddly enough, all you see is the word Array. That is telling you that you have reached a multi-dimensional array and have to dig deeper. Thanks to var_dump you have the tools to do so.

Place the slashes back on echo $details, on line 55, as in:

//echo $details; 

and de-comment

echo $details['Santorum'];

Once again, live view simply displays Array.

Let's dig one level deeper and de-comment the next line,
//echo $details['Santorum']['spouse']; Now we're getting somewhere. You should see Karen Santorum in live view. Substitute Obama or one of the other candidates for Santorum and you will see the name of their spouse. Or, as shown on line 61, substitute one of the other characteristics such as year_born to pull that specific data.

Experiment. Extract more details about Rick Santorum  such as his political party and the year he was born. Now do the same for at least one other candidate.

What if you wanted to pull all of the data about a specific characteristic such as religion or state? De-comment line 62 and check out the result. Feel free to play around and explore various aspects of extracting data from a multi-dimensional array. It can be a useful skill if you ever find yourself trying to extract data from a complicated api.

Next: Introduction to Databases (and my sql) 

Print Friendly, PDF & Email