Arrays

There are two ways of adding values to an array: with the [] operator, which is unique to arrays; and with the array() pseudo-function. You should use [] when you want to add items to an existing array and use array() to create a new array.

To sum all this up in code, Listing 29.2 shows a script that creates an array without specifying keys, adds various items to it both without keys and with keys of varying types, does a bit of printing, and then clears the array.

Listing 29.2. Manipulating Arrays

$myarr = array(1, 2, 3, 4);

$myarr[4] = "Hello"; $myarr[] = "World!"; $myarr["elephant"] = "Wombat"; $myarr["foo"] = array(5, 6, 7,

echo $myarr["elephant"];

echo $myarr["foo"][1];

?>

The initial array is created with four elements, to which we assign the values 1, 2, 3, and 4. Because no keys are specified, PHP automatically assigns keys for us starting at 0 and counting upwardgiving keys 0, 1, 2, and 3. Then we add a new element with the [] operator, specifying 4 as the key and "Hello" as the value. Next, [] is used again to add an element with the value "World!" and no key and then again to add an element with the key "elephant" and the value "wombat". The line after that demonstrates using a string key with an array valuean array inside an array (a multidimensional array).

The next three lines demonstrate reading back from an array, first using a numeric key, then using a string key, and then using a string key and a numeric key. Remember, the "foo" element is an array in itself, so that third reading line retrieves the array and then prints the second element (arrays start at 0, remember). The last line blanks the array by simply using array() with no parameters, which creates an array with elements and assigns it to $myarr.

The following is an alternative way of using array() that allows you to specify keys along with their values:

$myarr = array("key1" => "value1", "key2" => "value2", 7 => "foo", 15 => "bar");

Which method you choose really depends on whether you want specific keys or want PHP to pick them for you.

Was this article helpful?

0 0

Post a comment