Section 6.1. Array Fundamentals


6.1. Array Fundamentals

When working with arrays, there are two new terms: elements and indexes. Elements are the values that are stored in the array. Each element in the array is referenced by an index that identifies the element by any other unique element in the array. The index value can be a number or a string, but it must be unique. You can think of an array like a spreadsheet or a database that has only two columns. The first column selects the row in the spreadsheet, while the second column contains a stored value.

6.1.1. Associative Versus Numeric Indexed Arrays

Numeric arrays use numbers as their indexes while associative arrays use stings. When using associative arrays, you must supply an index string each time you add an element. Numeric arrays allow you to just add the element, and PHP automatically assigns the first free number, starting at 0.

Be careful, since most people tend to start counting at 1 not 0. If you're not careful, you might end up being off by one when accessing your array. This is called an off-by-one error! The last element in a numeric array is accessed as the length of the array minus 1.


A common symptom of starting to access the values of your array at 1 instead of 0 is attempting to access the last value and finding it's not there! For instance, if you use a numeric array to store four elements and let PHP pick the number index values, the last value is stored under the index value of 4. For example, Table 6-1 shows a numeric array with five elements. Attempting to access the fifth value at location 5 would miss it, getting the sixth instead. Table 6-1 displays numeric arrays, starting with the number 0.

Table 6-1. A numeric array containing colors, starting at zero

Key

Value

0

Black

1

Blue

2

Red

3

Green

4

Purple


Internally, PHP stores numeric arrays in the same way it stores associative arrays. Numeric arrays are provided because they make it easier to loop through a set of data, since you need only to perform an addition on the key to access the next value.

6.1.2. Creating an Array

To create an array, you must specify the elements and index values. In Table 6-2, we show a sample associative array that uses household objects and relates them to strings that describe their shapes.

Table 6-2. An associative array that relates objects to their shapes

Key

Value

Soda Can

Cylinder

Note Pad

Rectangle

Apple

Sphere

Orange

Sphere

Phone book

Rectangle


The elements of an array can be anything, including strings, numbers, and even other arrays! The key field must be a scalar. Scalar values are simple values such as a number or text, including true or false, not data that can have more than one value such as an array. The key field of an array must also be unique. Should you attempt to assign a value using a key you specified already, the new value simply replaces the old value.

Short yet meaningful values for your index keys make your programs run faster, which will make them easier to maintain.

6.1.2.1. Assignment via array identifiers

Now that you know what can go into an array, you'll need a way to get values into the array. PHP provides two ways of assigning values to arrays. We'll discuss array identifiers for assignment first.

Array identifiers look like normal variable assignments except a pair of brackets ([]) are added after the name of the array variable. You can optionally add an index value between the brackets. If you don't supply an index, PHP automatically picks the lowest empty numeric index value for the array. For example, to assign the first two days of the week to a numeric indexed array, you would use:

 <?php $weekdays[]='Monday'; $weekdays[]='Tuesday'; ?> 

You could also specify the index values, which has the same end result as:

 <?php $weekdays[0]='Monday'; $weekdays[1]='Tuesday'; ?> 

If you do specify the index yourself, be careful not to skip over numbers:

 <?php $weekdays[0]='Monday'; $weekdays[1]='Tuesday'; $weekdays[3]='Wednesday'; ?> 

This code creates an array that doesn't have a value assigned for the index of 2. That might be OK, but if you're going through the array values sequentially and your code unexpectedly encounters a missing value, that'll cause problems, but not a PHP error.

6.1.2.2. Assignment using array

The other way to assign values to an array is to use the array function. The array function allows you to create your array and assign multiple elements all at once. The array takes pairs of index keys and values as parameters. It returns an array assigned to a variable. The elements to be assigned are separated by commas.

Example 6-1 creates a numeric array using array.

Example 6-1. Using the array function to create an array of weekdays

 <?php $weekdays=array('Monday',                 'Tuesday',                 'Wednesday',                 'Thursday',                 'Friday',                 'Saturday',                 'Sunday'); ?> 

The whitespace you see in this code makes adding elements to the array easier. You can create as many elements in the array as you wish.

In Example 6-2, we create an associative array using the format index => value.

Example 6-2. Creating an associative array of shapes

 <?php   $shapes=array('Soda Can' => 'Cylinder',                 'Note Pad' => 'Rectangle',                 'Apple' => 'Sphere',                 'Orange' => 'Sphere',                 'Phonebook' => 'Rectangle'); ?> 

When assigning array names, you need to be careful not to use the same name as another variable, since they share the same set of names. Assigning a variable to the same name as an existing array will overwrite the array without warning.


If you're not sure whether a variable is an array, you can use is_array. For example, you'd enter the code:

 <?php $yes = array('this', 'is', 'an array'); echo is_array($yes) ? 'Array' : 'not an Array'; echo "<br>"; $no = 'this is a string'; echo is_array($no) ? 'Array' : 'Not an Array'; ?> 

This outputs:

 Array Not an Array 

Since you know how to assign values to an array and how to find out whether a variable is an array, it's time to discuss retrieving those values.

6.1.2.3. Looping through and referencing array values

Items in an array may be individually accessed by including the key to the array in brackets after the name of the variable in the form $array[index]. Arrays referenced in a string that have a key value with whitespaces or punctuation must be enclosed in curly braces ({}). For example, Example 6-3 displays the value of the $shapes array for 'Note Pad'.

Example 6-3. Displaying one value from an array

 <?php   $shapes=array('Soda Can' => 'Cylinder',                 'Note Pad' => 'Rectangle',                 'Apple' => 'Sphere',                 'Orange' => 'Sphere',                 'Phonebook' => 'Rectangle');   print "A note pad is a {$shapes['Note Pad']}."; ?> 

Example 6-3 produces:

 The Note Pad is a Rectangle. 

In Example 6-4, a foreach loop displays all the values in an array. The foreach statement is handy, because it automatically advances and reads each value from an array until it reaches the last value n in the array. This eliminates having to remember 0-based arrays, and won't run beyond the length of an array, making it a very useful looping construct that avoids common logical errors. Example 6-4 shows an array's content using a loop.

Example 6-4. Display the contents of an array using a loop

 <?php $shapes=array('Soda Can' => 'Cylinder',               'Note Pad' => 'Rectangle',               'Apple' => 'Sphere',               'Orange' => 'Sphere',               'Phonebook' => 'Rectangle'); foreach ($shapes as $key => $value) {     print"The $key is a $value.<br>\n"; } ?> 

Example 6-4 produces:

 The Soda Can is a Cylinder.<br> The Note Pad is a Rectangle.<br> The Apple is a Sphere.<br> The Orange is a Sphere.<br> The Phonebook is a Rectangle.<br> 

The breaks, <br>, won't show up in your browser as they are HTML markup, adding line breaks after each sentence. Each string in the array was processed, so the loop stopped automatically.

6.1.2.4. Adding values to an array

To add values to the end of an existing array, you can use the array identifier. For example, to add Thursday to the $weekdays array:

 <?php $weekdays[] = "Thursday"; ?> 

To add another shape to your associative array, use a similar syntax:

 <?php $shapes["Megaphone"]= "Cone"; ?> 

This works even though the array was created using the array function. This leads us to the opposite problem.

6.1.2.5. Counting how many elements are in an array

You can use the count function to find out how many elements are currently assigned to an array. The count function is identical to sizeof and can be used interchangeably. Example 6-5 counts the elements in the $shapes array.

Example 6-5. Counting the elements in an array

 <?php $shapes=array('Soda Can' => 'Cylinder',               'Note Pad' => 'Rectangle',               'Apple' => 'Sphere',               'Orange' => 'Sphere',               'Phonebook' => 'Rectangle'); $numElements = count($shapes); print"The array has $numElements elements.<br>\n"; ?> 

Example 6-5 displays:

 The array has 5 elements. 

The print command in Example 6-5 is identical to echo, for the purposes of arrays. It doesn't matter whether your array is associative or numeric when count sizes up your array. If you want the array to sort your data in alphabetical order, you'd use sort.

6.1.2.6. Sorting arrays

This function sorts an array. Elements are arranged from lowest to highest after this function is completed. Numbers are sorted numerically, while strings are sorted alphabetically. This function assigns new keys for the elements in an array. It removes any existing keys you may have assigned, rather than just reordering the keys.

You need to be cautious when sorting arrays with mixed type values, because sort can produce unpredictable results.


Using the shapes example from Example 6-5, you can sort alphabetically. The code would look like Example 6-6.

Example 6-6. Using sort to alphabetize

 <?php $shapes = array("rectangle", "cylinder", "sphere"); sort($shapes); //The foreach loop selects each element from the array and assigns its value to $key //before executing the code in the block. foreach ($shapes as $key => $val) {  echo "shapes[" . $key . "] = " . $val . "<br>"; } ?> 

Example 6-6 outputs to:

 shapes[0] = cylinder shapes[1] = rectangle shapes[2] = sphere 

As you can see, the shapes have been sorted alphabetically. Table 6-3 shows an optional second parameter sort_flags that can be used to modify the sorting behavior using these values.

Table 6-3. sort_flags

sort_flag

Definition

sort_regular

Compares items normally, but doesn't change types

sort_numeric

Compares items numerically

sort_string

Compares items as strings

sort_locale_string

Compares items as strings, based on the current locale


You've learned a lot about arrays; now let's move on to multidimensional arrays that hold more elements instead of just simple values.

6.1.3. Multidimensional Arrays

While we've only shown arrays that hold simple values like strings so far, remember that an array can also store another array as an element. Multidimensional arrays exploit the fact that an array can have another array as an element. Each set of keys and values represents a dimension. Multidimensional arrays have a key and value set for each dimension. Don't worry if that sounds complicated; again, it's really just an array inside of an array, like those Russian dolls that open up to contain yet another smaller doll!

Expanding upon your shapes array, we create a new associative array called $objects with keys that are the names of the objects. Each element of the $objects array is another associative array containing the keys shape, color, and material with the associated values as the elements. Table 6-4 shows you what data is being stored.

Table 6-4. A multidimensional array that now stores shape, color, and material for each object

First key

Second key

Value

Soda can

Shape

Cylinder

 

Color

Red

 

Material

Metal

Note Pad

Shape

Rectangle

 

Color

White

 

Material

Paper

Apple

Shape

Sphere

 

Color

Red

 

Material

Fruit

Orange

Shape

Sphere

 

Color

Orange

 

Material

Fruit

Phonebook

Shape

Rectangle

 

Color

Yellow

 

Material

Paper


To create the array in Table 6-4, use the array function like that in Example 6-7.

Example 6-7. Creating a multidimensional array

 <?php $objects=array('Soda Can' =>    array('Shape'    => 'Cylinder',                                       'Color'    => 'Red',                                       'Material' => 'Metal'),                'Note Pad' =>    array('Shape'    => 'Rectangle',                                       'Color'    => 'White',                                       'Material' => 'Paper'),                'Apple' =>       array('Shape'    => 'Sphere',                                       'Color'    => 'Red',                                       'Material' => 'Fruit'),                'Orange' =>      array('Shape'    => 'Sphere',                                       'Color'    => 'Orange',                                       'Material' => 'Fruit'),                'Phonebook' =>  array('Shape'    => 'Rectangle',                                       'Color'    => 'Yellow',                                       'Material' => 'Paper')); echo $objects['Soda Can']['Shape']; ?> 

Example 6-7 displays:

 Cylinder 

We're able to access the second dimension of the array by using a second set of brackets ([]) to specify the second key. If the array has more dimensions than just two, you must specify the key for each dimension. True to form, if you access $objects['Orange'], you would get an array.

Example 6-8 displays all of the elements of both arrays.

Example 6-8. Displaying a multidimensional array

 <?php foreach ($objects as $obj_key => $obj) {   echo "$obj_key:<br>";   while (list ($key,$value)=each ($obj))   {      echo "$key = $value ";   }  echo "<br>"; } ?> 

The code displays something like Figure 6-1.

Figure 6-1. The multidimensional array displays in the browser


However, there's more than one way to display an array.

There's also a built-in function to display an array all in one step, called var_dump. If you specify your array from Example 6-7 like this:

 echo var_dump($ojbects); 

you see:

 array(5) { ["Soda Can"]=> array(3) { ["Shape"]=> string(8) "Cylinder" ["Color"]=> string(3) "Red" ["Material"]=> string(5) "Metal" } ["Note Pad"]=> array(3) { ["Shape"]=> string(9) "Rectangle" ["Color"]=> string(5) "White" ["Material"]=> string(5) "Paper" } ["Apple"]=> array(3) { ["Shape"]=> string(6) "Sphere" ["Color"]=> string(3) "Red" ["Material"]=> string(5) "Fruit" } ["Orange"]=> array(3) { ["Shape"]=> string(6) "Sphere" ["Color"]=> string(6) "Orange" ["Material"]=> string(5) "Fruit" } ["Phonebook"]=> array(3) { ["Shape"]=> string(9) "Rectangle" ["Color"]=> string(6) "Yellow" ["Material"]=> string(5) "Paper" } } 

While it's not formatted as nicely as Example 6-8, it's less work and can take an array as its input. This is a great tool for debugging the values in an array. The numbers after the data types indicate how long each one is; for instance in this example, there are five elements in the first level of the array and each string has a different length based on its contents. There are general tools available for debugging your PHP code, and there are also PHP tools that can help you debug your code yourself, without the purchase of a separate program. Xdebug is a free debugger available from http://xdebug.org/. Zend Studio, available from http://www.zend.com/store/products/zend-studio/, includes a debugger as part of its Integrated Development Environment (IDE). An IDE includes editing, testing, and debugging in one application.

6.1.4. Extracting Variables from an Array

PHP provides a shortcut for placing elements in an array into variables, where the variables have the same names as the keys. This works for associative arrays only, unless of course, you specify a prefix that we'll talk about next. The exTRact function takes an array as a parameter and creates the local variables, as shown in Example 6-9.

Example 6-9. Using extract on an associative array

 <?php $shapes=array('SodaCan' => 'Cylinder',               'NotePad' => 'Rectangle',               'Apple' => 'Sphere',               'Orange' => 'Sphere',               'PhoneBook' => 'Rectangle'); extract($shapes); // $SodaCan, $NotePad, $Apple, $Orange, and $PhoneBook are now set echo $Apple; echo "<br>"; echo $NotePad; ?> 

Example 6-9 produces browser output like that in Figure 6-2.

Figure 6-2. The values from the array now appear in their own variables


Notice that the spaces were removed from the key values in the $shapes array. Although they wouldn't have caused an error, they also wouldn't be accessible as variables, since variable names cannot have spaces. You need to use underscores instead of spaces in variable names. Also, if a variable already exists with the same name as a key in the array to expand, its value is overwritten by the value from the expanded array.

One way to prevent possibly overwriting a variable you're already using is to include a second set of parameters to expand that specify a prefix to be prepended to the name of each variable you extract from the array. It's specified using this syntax:

 expand($array,EXtr_PREFIX_ALL,"the prefix"); 

Example 6-10 demonstrates the use of the EXtr_PREFIX_ALL option for exTRact.

Example 6-10. Using extract with the EXTR_PREFIX_ALL directive

 <?php $Apple="Computer"; $shapes=array('SodaCan' => 'Cylinder',               'NotePad' => 'Rectangle',               'Apple' => 'Sphere',               'Orange' => 'Sphere',               'PhoneBook' => 'Rectangle'); extract($shapes,EXTR_PREFIX_ALL,"shapes"); // $shapes_SodaCan, $shapes_NotePad, $shapes_Apple, $shapes_Orange, and //$shapes_PhoneBook are now set echo "Apple is $Apple.<br>"; echo "Shapes_Apple is $shapes_Apple"; echo "<br>"; echo "Shapes_NotePad is $shapes_NotePad"; ?> 

Example 6-10 returns:

 Apple is Computer. Shapes_Apple is Sphere Shapes_NotePad is Rectangle 

The EXTR_PREFIX_ALL keyword allows you to use extract on a numeric array. Example 6-11 creates a numeric array, calls extract on it, and then accesses the variable for the zero position element.

Example 6-11. Using EXTR_PREFIX_ALL on a numeric array

 <?php $shapes=array( 'Cylinder',                'Rectangle'); extract($shapes,EXTR_PREFIX_ALL,"shapes"); echo "Shapes_0 is $shapes_0 <br>"; echo "Shapes_1 is $shapes_1"; ?> 

Example 6-11 displays:

 Shapes_0 is Cylinder Shapes_1 is Rectangle 

PHP also gives you a function, called compact, that does the opposite of extract.

6.1.4.1. Using compact to build an array from variables

The compact function is the complement of extract. It takes the variables as parameters individually, as arrays, or a combination of both. The compact function creates an associative array whose keys are the variable names and whose values are the variable's values. Any names in the array that don't correspond to actual variables are skipped. Arrays of variables as parameters are automatically expanded. Here's an example of compact in action:

 <?php $SodaCan='Cylinder'; $NotePad='Rectangle'; $Apple = 'Sphere'; $Orange = 'Sphere'; $PhoneBook = 'Rectangle'; $shapes=compact('SodaCan', 'Note Pad', 'Apple', 'Orange', 'PhoneBook'); echo var_dump($shapes); ?> 

This produces something like Figure 6-3 in your browser.

Figure 6-3. The browser displaying the variable dump for a compact created array


6.1.5. Array Functions in PHP

Although we've already discussed several array functions such as count, there are many more. Following are some of the most common ones that we haven't discussed yet; for a full listing, search http://www.php.net.


Reset( array)

Takes an array as its argument and resets the pointer to the beginning of the array. The pointer is how PHP keeps track of the current element in an array when working with functions that can move around in arrays.


Array_push( array,elements)

Adds one or more elements to the end of an existing array. For example, array_push($shapes,"rock","paper","scisors"); adds those three elements to an array called $shapes.


Array_pop( array)

Returns and removes the last element of an array. For example, $last_element=array_pop($shapes); removes the last element from $shapes and assigns it to $last_element.


Array_unshift( array,elements)

Adds one or more elements to the beginning of an existing array. For example, array_unshift($shapes,"rock","paper","scisors"); adds three elements to the beginning of an array called $shapes.


Array_shift( array)

Returns and removes the first element of an array. For example, $first_element=array_unshift($shapes); removes the first element from $shapes and assigns it to $first_element.


Array_merge( array,array)

Combines two arrays together and returns the new array. For example, $combined_array=array_merge($shapes,$sizes); combines the elements of both arrays and assigns the new array to $combined_array.


Array_keys( array)

Returns an array containing all of the keys from the supplied array. For example, $keys=array_keys($shapes); assigns an array to $keys that consists of only the keys like "Apple" and "Note Pad" from the array in Example 6-2.


Array_values( array)

Returns an array containing all of the values from the supplied array. For example, $values=array_values($shapes); assigns an array to $values that consists of only the element values like "Sphere" and "Rectangle" from the array in Example 6-2.


Shuffle( array)

Resorts the array in random order. The key values are lost when the array is shuffled because the returned array is a numeric array. For example, shuffle($shapes); could place the value "Rectangle" in $shapes[0] using the array from Example 6-2.

We've covered most everything you need to get going with PHP; it's now time to start introducing databases and MySQL in particular, then tackle how MySQL and PHP work synergistically.



Learning PHP and MySQL
Learning PHP and MySQL
ISBN: 0596101104
EAN: 2147483647
Year: N/A
Pages: 135

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net