>
Arrays actually act like both hash tables (associative arrays) and indexed arrays (vectors).
Single Dimension Arrays
PHP supports both scalar and associative arrays. In fact, there is no difference between the two. You can
create an array using the list or array functions, or you can explicitly set each array element value.
$a[0] = "abc";
$a[1] = "def";
$b["foo"] = 13;
You can also create an array by simply adding values to the array.
$a[] = "hello"; // $a[2] == "hello"
$a[] = "world"; // $a[3] == "world"
Arrays may be sorted using the asort, arsort, ksort, rsort, sort, uasort, usort, and uksort
functions depending on the type of sort you want.
You can count the number of items in an array using the count function.
You can traverse an array using next and prev functions. Another common way to traverse an array is to use the each function.
Multi-Dimensional Arrays
Multi-dimensional arrays are actually pretty simple. For each dimension of the array, you add another
[key] value to the end:
$a[1] = $f; # one dimensional examples
$a["foo"] = $f;
$a[1][0] = $f; # two dimensional
$a["foo"][2] = $f; # (you can mix numeric and associative
indices)
$a[3]["bar"] = $f; # (you can mix numeric and associative
indices)
$a["foo"][4]["bar"][0] = $f; # four dimensional!
You can "fill up" multi-dimensional arrays in many ways, but the trickiest one to understand is how to
use the array command for associative arrays. These two snippets of code fill up the one-dimensional array in the same way:
# Example 1:
1: $a["color"] = "red";
2: $a["taste"] = "sweet";
3: $a["shape"] = "round";
4: $a["name"] = "apple";
5: $a[3] = 4;
# Example 2:
1: $a = array(
2: "color" => "red",
3: "taste" => "sweet",
4: "shape" => "round",
5: "name" => "apple",
6: 3 => 4
7: );
The array function can be nested for multi-dimensional arrays:
1: <?
2: $a = array(
3: "apple" => array(
4: "color" => "red",
5: "taste" => "sweet",
6: "shape" => "round"
7: ),
8: "orange" => array(
9: "color" => "orange",
10: "taste" => "sweet",
11: "shape" => "round"
12: ),
13: "banana" => array(
14:
15: "color" => "yellow",
16: "taste" => "paste-y",
17: "shape" => "banana-shaped"
18: )
19: );
20: echo $a["apple"]["taste"]; # will output "sweet"
21: ?>