php 101


We've seen how variables can store a single value (which could be a string, or a number, or virtually any type of object). But what happens when you have a lot of variables to keep track of, which are all part of a set? For example, let's say you performed a query on your database which returned the test scores of all 30 of your students. It would be a major pain to create a new variable for each score. Instead, you'd want to use an "array," which you can think of sort of like a folder - a single variable storing lots of values.

There are two basic types of arrays in most programming languages. In PHP, the two types are called "indexed" and "associative" arrays. An indexed array is a simple list of values, and it looks like this:

Note that we used a function called "print_r()" here instead of echo(). If you try to "echo" an array back to the screen, you'll find that you can't. An array can be gigantic, and can have many "dimensions" (think of folders within folders). So instead, PHP just prints the string "Array()" to the screen. But during testing and development, it's sometimes useful to force PHP to print out a whole array, and the print_r() function does this for us.

If you want to get at the actual values in an indexed array, you have to refer to them by number. In programming languages, the first element in an array is the 0th, the second element is the 1st, and so on. So try this:

You'll see the first three elements of the array printed to the screen (without any line breaks, since we didn't add them, and HTML ignores whitespace). But what if your database query emitted both the names and scores of the students in your class? In that case, you'd want to use an "associative" array, which works more like a phone book, allowing you to look up an array element by name. An associative array looks like this:

That's more like it! Later we'll learn how to "iterate" over all elements in an array to print them all out.

If you want to append a new item to the end of an indexed array, simply use:

The new value will be plopped onto the end of the array. If you want to add a value to an associative array, the process is similar, but you need to give the key name at the same time: