aaron lee

the life of a medical student

Table of Contents

  1. Arrays

Arrays

Before heading into the control flow that PHP has to offer, I thought it would be important to talk a bit about how arrays work in PHP. In PHP, the simplest way to think about every array is that they are essentially associative arrays. That is to say that every entry in the array has an associated key and value pair. This is not so different from the way that Perl arrays work, but there is one crucial difference.

The difference is that in PHP, there is no use of the ‘at’ symbol (@) for any meaning. Instead, you simply treat arrays like any other variable with the dollar symbol ($). That said, let’s move on to some examples of how arrays work.


1. <?php
2. $pi = array( 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9 );
3.
4. print_r($pi);
5. print(”The first few digits of pi are:”
6. .$pi[0].$pi[1].$pi[2].$pi[3].$pi[4].”<BR>”);
7.
8. $fruitcolors = array(
9. “bannana” => “yellow”,
10. “orange” => “orange”,
11. “apple” => “red”);
12.
13. print(”The color of an apple is ”
14. .$fruitcolors[’apple’].”<BR>”);
15.
16. ?>

First thing that you should notice is that arrays are handled in nearly the same manner as other languages in that you enclose the key with a set of square brackets ([]). Line 2 is the creation of an array using the function array. This function simply returns an array with automatic indexing if no index is provided as in Line 2. The print_r function is used to print the array in Line 4, and in Line 5, the way to access the elements of the array are shown. As I said before, the method is identical to many other programming languages.

In Lines 8-11, the array $fruitcolors is created. This time, automatic indexing is not used because the indices are provided (”bannana”, “orange”, and “apple”). These become the keys and the repective colors become the values. The symbol => is used to associate the key from the value and the delimiter is obviously the comma (,), used to separate the
key/value pairs. Line 13-14 show how to retrieve a value with a given key.

PHP supports multi-dimensional arrays by simply allowing you to put arrays within other arrays. This is illustrated below:


1. <?php
2.
3. $matrix = array(array(1, 2), array(3, 4));
4.
5. print(”Matrix value at position 1, 2 is:
6. “.$matrix[1][2].”<BR>);
7.
8. ?>

The multi-dimensional array is created using multiple calls to array. Line 3 simply creates a 2×2 matrix with the values 1, 2 in the first row, and 3, 4 in the second. Lines 5-6 show how to access the values within multi-dimensional arrays using two indices.

As you can see, the array implementation in PHP is both flexible and powerful. Coupled with the vast number of built-in functions that PHP provides to handle arrays, they are a very useful data structure. The size of an array is also dynamic, which is a nice change from the static arrays from C.

Posted on 30 Sep

Post A Comment