6.1. Array FundamentalsWhen 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 ArraysNumeric 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.
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.
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 ArrayTo 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.
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 identifiersNow 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 arrayThe 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
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
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 valuesItems 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
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
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 arrayTo 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 arrayYou 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
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 arraysThis 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.
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
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.
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 ArraysWhile 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.
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
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
The code displays something like Figure 6-1. Figure 6-1. The multidimensional array displays in the browserHowever, 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 ArrayPHP 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
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 variablesNotice 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
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
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 variablesThe 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 array6.1.5. Array Functions in PHPAlthough 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.
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. |