PHP – Lesson 07a: Arrays Overview

In This Lesson


Arrays

What is an array?

An array lets you store multiple values for a variable in a single association. For instance, let’s say we want to have many varieties of fruit. You could have an array of fruit, whose values could be any one of apples, oranges, grapes, or pears.

Three types of arrays

There are three main types of arrays:

  1. indexed array
  2. associative arrays
  3. multidimensional array

All types use “keys” to assign values of each array item, but they use the keys differently.


Indexed Arrays

All arrays have 2 components to each item within the array: key and value. The key is like a bookmark that makes the value of the item easy to locate. In an indexed array, the “key” portion of the array item is always an integer (whole number). This way we can let PHP automatically assign numeric keys to each array item in the order that the values are assigned.

For instance, if we use our fruit example from above, we could declare a new array called $fruit and immediately assign values to the array like this:

$fruit = array("apples","oranges","grapes","pears");

What this does is create an array called $fruit, and assign the keys and values as follows:

 

$fruit : indexed array
KEYS VALUES
0 apples
1 oranges
2 grapes
3 pears

Notice how the “first” numeric key we see assigned is “0.” It is very important to understand that computers like to start counting at 0 (zero). So even though there are 4 items in the array listed above, the numeric keys range from 0-3. Don’t let this trip you up in your logic; just remember that arrays start the count at 0.

Inspecting an array

So in the $fruit example above, you can see the keys and values because we outlined them in a table for demonstration purposes. But how could you get this information through PHP?

There is a function that we use to inspect arrays so that you can see exactly what’s inside of them:

  • print_r()

So let’s say we already declared our $fruit array as listed above. If we use “print_r()” on the $fruit array, it will display all of the items’ keys and respective values:

print_r($fruit);

…will return to the browser:

Array ( [0] => apples [1] => oranges [2] => grapes [3] => pears )

But if you want to see it separated out in an even clearer way, you can wrap <pre></pre> tags around the function like this:

echo "<pre>";
print_r($fruit);
echo "</pre>";

…to output the following to the browser with line breaks:

Array

(

[0] => apples

[1] => oranges

[2] => grapes

[3] => pears

)

In addition to creating an indexed array as we saw above, you can also create the same array of fruit by deliberately assigning values to each numeric index key. See below:

<?php
$fruit[0] = "apples";
$fruit[1] = "oranges";
$fruit[2] = "grapes";
$fruit[3] = "pears";
?>

In fact, we could at any time add a new item to an array simply by declaring it anywhere in the php:

$fruit[4] = "kiwi";

This would add the “kiwi” value to the fourth position of the array.

For a working example file with comments, download the “array_indexed.php” testing file and load it into your webserving development folder.

Another tidbit….

Before moving on, it is also useful to note that array values can hold many data types, like NULL, integers, floats, strings, or even other arrays. You can have an array whose different keys hold completely different data types. For instance, here is an array holding personal info about an employee using many data types:

$employee = array("Tom","Robertson",21,13.5,"male","cashier",2.5);

And one more last quick tidbit….

We’ve explored how to inspect an array with the print_r() function, but that is just really for the programmer to use in testing. If you want to actually print an array item to screen in a normal way that just displays the value, you can use echo, like this example:

echo $fruit[4];

This would display the value of the fourth key from the $fruit array: kiwi

Associative Arrays

What’s the difference?

An associative array is different from an indexed array in that the associative type can hold other data types for its keys besides integers. With an associative array, we can pair information in a way that associates the key to value so that the array is more informative to us than an indexed type.

If we use the last example of the indexed array, $employee, you realize that we have no idea what those values represent, other than positions 0-6 of the array. But if we make it an associative array, the representations becomes more evident:

$employee = array(

"firstname"=>"Tom",
"lastname"=>"Robertson",
"age"=>21,
"payrate"=>13.5,
"sex"=>"male",
"position"=>"cashier",
"years_service"=>2.5

);

If you inspect this array with <pre></pre> tags around the print_r() function, it will print this to the browser:

$employee = array(

[firstname] => “Tom”
[lastname] => “Robertson”
[age] => 21
[payrate] => 13.5
[sex] => “male”
[position] => “cashier”
[years_service] => 2.5

)

Notice that the keys are in brackets instead of quotes now. Remember, data wrapped in square brackets like this indicates that it is a key in an array. Also notice that the commas are gone after each line, and that it doesn’t display our terminator at the end. I am pointing this out in the event you try to copy and paste the code to make it work as an array definition; it won’t work. You will need to copy the php code that DEFINES the array, not the output of the print_r() function.

For a working example file with comments, download the “array_associative.php” testing file and load it into your web serving development folder.

Multidimensional Arrays

Now that we have a concept of how indexed and associative arrays work, let’s briefly look at multidimensional arrays. I say “briefly” because these are a little bit more advanced, and it might take a little bit of practical application later before you fully grasp the concept of how they are useful. So don’t worry if you don’t completely get it right now!

Basically, a multidimensional array is simply an array that contains at least one other array in is as a value. Sometimes you need to hold more complex sets of data in a single variable than just an associative array. Let’s look back to the $fruit example to see one way of thinking about it.

Instead of calling out just apples, oranges, grapes, and pears, let’s say we need to hold more information about the fruit types, like “citrus, melons, berries.” We could do this:

$fruit = array(

"citrus" => array("oranges","lemons","limes"),
"melons" => array("watermelon","honeydew","cantelope"),
"berries" => array("strawberries","raspberries","blueberries")

);

The top level array is like an associative one, whose key => value pair holds two critical pieces of information, but the value of each item in the top level array happens to contain MULTIPLE values….So we have to assign a new array to each fruit type’s value. In the example above, we have indexed arrays nested inside of a top level associative-structure; the net result is that the entire package is a “multidimensional array.”

We could even take it a step further if we wanted and include the information about how each fruit grows. Take a look:

$fruit2 = array(

“tree” => array(“citrus” => array(“oranges”,”lemons”,”limes”)),
“vine” => array(“melons” => array(“watermelon”,”honeydew”,”cantelope”)),
“berries” => array(“strawberries”,”raspberries”,”blueberries”))
);

 

If you type these arrays into a php file and print them back to the browser wrapping the print_r() function in <pre></pre> tags, you will see a clear outline of how these arrays are organized. You can think of them like files and folders in a computer file system. This might help you better understand the visual and conceptual hierarchy of a multidimensional arrays possibilities.

For a working example file with comments, download the “array_multidimensional.php” testing file and load it into your web serving development folder.

 

Superglobal Arrays

What is a superglobal array?

A Superglobal Array is a distinctly different type of array from the ones already mentioned. Superglobals are predefined in PHP and perform common and useful tasks for you. They are also ALWAYS indicated in this format: $_CAPITALLETTERS. Below I will list some common ones, but there are a lot more that are very useful. You can find a complete and updated list with decriptions and use examples at http://uk.php.net/manual/en/language.variables.superglobals.php. You should also read the class tutorial on $_SERVER superglobals for more in depth understanding of the $_SERVER superglobal.

  • $_POST and $_GET :: used to pass variables from forms.
  • $_SERVER :: contains information stored by the webserver, like filename, hostname, pathname….
  • $_FILES :: used for uploading files to the server via PHP
  • $_SESSION :: stores information from page to page so the user doesn’t lose it (i.e. user login credentials)

 


Indexed Array Introduction Lecture (4:30)

Note: This lecture is a slideshow walk-through explanation of the web notes above on this page.


Indexed Array Introduction Lecture (12:38)

 

Associative Arrays Introduction Lecture (4:01)

Note: This lecture is a slideshow walk-through explanation of the web notes above on this page.


Associative Arrays (7:59)

 

Multidimensional Arrays

Download the instructor’s Multidimensional Arrays PDF to learn more about them. For a working example file with comments, download the “array_multidimensional.php” testing file and load it into your web serving development folder.