Arrays Revisited

An array is a way to group an arbitrary amount of data into a single variable. In PHP, arrays are ordered maps that operate very differently from arrays in languages such as C/C++, BASIC, Java, and C#. PHP arrays, often called associative arrays, are collections of any type of data, including objects and other arrays, which have a key or index associated with them. These arrays only use as much space as the data contained in them, and the data is always stored in the order added, regardless of key value. This contrasts sharply with arrays that contain a fixed number of "slots" (typically numbered starting at zero) for which the slot name and the position in the array are identical. Figure 5-1 shows a conception of the two versions.

Figure 5-1. Different approaches to array use and storage.

Creating Arrays and Adding Data

Arrays are typically created with the array language construct, including an optional list of contents for the array. You can choose to specify a key for each value added by using the => operator. (This key will either be an integer or a string.) If you elect not to specify one (for example, if you are creating a simple list or collection of data), PHP will choose an integer-typed one for you that starts at the number zero.

  <?php   //   // PHP is assigning keys for me, starting at 0   //   $airplanes = array("Piper", "Cessna", "Beech", "Cirrus");   //   // We're using our own key names here now.   //   $home = array("size" => 1800, "style" => "ranch",                 "yearBuilt" => 1955, "numBeds" => 3,                 "numBaths" =>2, "price" => 150000); ?> 

Any existing data in the variables $airplanes or $home is overwritten. You can also create an array by adding a value to an unassigned variable (or a variable that is not currently of type array) using square brackets.

 <?php   //   // creates a new array with a single value with key 0.   //    $stockedItems[] = "Mens Pleated Cotton Pants, Green"; ?> 

Another way to create arrays is to copy them from another variable. When you copy an array in PHP, a new array is created with all the contents of the existing one duplicated.

 <?php   //   // creates a complete copy of the $airplanes array including   // both keys and values.   //   $usedAirplanes = $airplanes; ?> 

Adding data to the arrays is done by specifying the key for which you want a given piece of data to appear. If you do not specify a key for a given value, an integer is assigned for you by PHP:

 <?php   //   // This array will have values with keys 0, 1, 2, 3 and 4.   //   $noises = array("moo", "oink", "meow", "baaaa", "roar!");   $noises[] = "bark";             // this is at key/index 5   $noises[] = "chirp";            // 6   $noises[7] = "quack"; ?> 

There is no requirement for these integer values to be in any particular order. New values are always added to the end of the array, and the integer key counter is always set to one greater than the largest positive integer value seen thus far.

 <?php   //   // non-consecutive numbers are ok.  They're just added   // to the end of the array!   //   $noises[123] = "hissssssss";   //   // NOTE: this is added to the end of the array, AFTER item   // 123.   //   $noises[11] = "neigh";   //   // this item will come at key/index 124.   //   $noises[] = "gobble gobble"; ?> 

If you were to print the contents of the $noises array using the var_dump function, you would see something similar to the following (which we have helpfully formatted):

 array(11) { [0]=> string(3) "moo"             [1]=> string(4) "oink"             [2]=> string(4) "meow"             [3]=> string(5) "baaaa"             [4]=> string(5) "roar!"             [5]=> string(4) "bark"             [6]=> string(5) "chirp"             [7]=> string(5) "quack"             [123]=> string(10) "hissssssss"             [11]=> string(5) "neigh"             [124]=> string(13) "gobble gobble" } 

As mentioned before, instead of an integer key, you can use strings:

 <?php   //   // There are five key/value pairs in this array initially.   //   $noisesByAnimal = array("cow" => "moo", "pig" => "oink",                           "cat" => "meow", "lion" => "roar!");   //   // Adding two more key/value pairs.   //   $noisesByAnimal["dog"] = "bark";   $noisesByAnimal["bird"] = "chirp"; ?> 

Things can start to get interesting when you mix integer key names and string key names:

 <?php   //   // the value 'quack' actually has a key/index of 0 !!   //   $noisesByAnimal["snake"] = "hisssssss";   $noisesByAnimal[] = "quack"; ?> 

We now have an array with both string and integer key names. The item at index/key 0 is the last in the array, and its key is an integer instead of a string. PHP has no serious problems with this mixing, with one exception: The string value key "0" and integer key 0 are treated as the same, whereas "1" and 1 are considered different. To avoid problems such as these, we will generally try to avoid this. You should also be asking yourself why you are using two types for the key names, and whether your code would be more legible and maintainable if you were to stick to a more consistent scheme.

Accessing Elements in Arrays

You can access an element of an array by specifying its key, as follows:

 <?php   $breads = array("baguette", "naan", "roti", "pita");   echo "I like to eat ". $breads[3] . "<br/>\n";   $computer = array("processor" => "Muncheron 6000",                     "memory" => 2048, "HDD1" => 80000,                     "graphics" => "NTI Monster GFI q9000");   echo "My computer has a " . $computer['processor']        . " processor<br/>\n"; ?> 

You can also use a variable to specify the key:

 <?php   $x = 0;   echo "Today's special bread is: " . $breads[$x] . "<br/>\n"; ?> 

String-based keys get slightly complicated when we use PHP's ability to embed variables within double-quoted strings. In this situation, accessing values with integer and variable keys is no problem, but string-typed ones can be a bit problematic.

 <?php   //   // Example 1   // This is no problem, because PHP easily finds the '2'   //   echo "I like to eat $breads[2] every day!<br/>\n";   //   // Example 2   // To use constants in arrays inside of strings, we must use   // complex notation:   //   define('NUMBER_CONSTANT, 2);   echo "I like to eat {$breads[NUMBER_CONSTANT]}. <br/>\n";   //   // Example 3   // This also works without troubles.   //   $feature = "memory";   echo "My PC has $computer[$feature]MB of memory<br/>\n";   //   // Example 4, 5   // Neither of these will work, and both will print an error.   //   echo "My PC has a $computer['processor'] processor<br/>\n";   echo "My PC has a $computer[""processor""] processor<br/>\n";   //   // Example 6, 7   // These will work just fine. The first one is preferred:   //   echo "My PC has a {$computer['processor']} processor<br/>\n";   echo "My PC has a $computer[processor] processor<br/>\n";   //   // Example 8   // Outside of a quoted string though, you should never use   // this syntax:   //   echo $computer[processor]; ?> 

When trying to specify a string key name within a string, you cannot use quotes (see Examples 4 and 5), which leads to confusion. PHP produces one of the following errors on output:

 Parse error: syntax error, unexpected   T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE   or T_NUM_STRING in /home/httpd/www/php/arrays.php on line 218 Parse error: syntax error, unexpected '"', expecting T_STRING   or T_VARIABLE or T_NUM_STRING in   c:\Inetpub\wwwroot\php\arrays.php on line 218 

You should strive to use the complex variable expansion syntax (see the section "More on Entering Strings" in Chapter 2, "The PHP Language") shown in Example 6. Another syntax that allows you to specify the key name without quotes (shown in Example 7) will work, but that is discouraged. If you try to use it outside of a double-quoted string, you will receive a warning:

 Notice: Use of undefined constant processor  assumed   'processor' in /home/httpd/php/arrays.php on line 225 

You will also run into problems if there is a constant with the same name as the unquoted string. (The constant's value will be used there instead.)

If you attempt to reference an array index that does not exist, as follows:

 <?php    echo "My PC has a {$computer['soundcard']} sound card<br/>\n"; ?> 

This will produce an output similar to the following:

 Notice: Undefined index: soundcard in   c:\Inetpub\wwwroot\phpwasrc\chapter05arrays.php on line 336 

Deleting Elements and Entire Arrays

To remove an element from an array variable, simply call the unset method and specify the key that you wish to unset.

 <?php   $drinks = array("Coffee", "Café au Lait", "Mocha", "Espresso",                   "Americano", "Latte");   unset($drinks[3]);    // removes "Espresso" from the array. ?> 

Now this array no longer has an item at index 3 ("Mocha" remains at index 2 and "Americano" remains at index 4). To delete an entire array, unset the variable:

 <?php   unset($drinks);   // $drinks is now empty/unset. ?> 

Counting Elements in an Array

To find out how many elements an array contains, you can call the count method in PHP. This is most commonly used to see how many elements there are in a top-level array:

 <?php   $drinks = array("Coffee", "Café au Lait", "Mocha", "Espresso",                  "Americano", "Latte");   $elems = count($drinks);   //   // The following prints out 6   //   echo "The array \$drinks has $elems elements<br/>\n"; ?> 

Core Web Application Development With PHP And MYSQL
Core Web Application Development with PHP and MySQL
ISBN: 0131867164
EAN: 2147483647
Year: 2005
Pages: 255

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: