- PHP arrays
are an ordered map (a type that that associates keys and values)
- Arrays can have any size and contain any type of value; no danger of going beyond array bounds
$my_array[0] = 25;
$my_array[1] = "Bisons";
- Arrays that use non-integer indexes/keys are often called
associative arrays
$capitals["CO"] = "Denver";
$capitals["AR"] = "Little Rock";
- Initialize an array
$colors = array("red", "green", "blue");
echo $colors[0]; // red
echo count($colors); // 3
$capitals = array("CO" => "Denver", "AR" => "Little Rock");
echo $capitals["CO"]; // Denver
echo count($capitals); // 2
- Print contents of an array for debugging
print_r($colors);
produces:
Array
(
[0] => red
[1] => green
[2] => blue
)
print_r($capitals);
produces:
Array
(
[CO] => Denver
[AR] => Little Rock
)
- Looping through an array
// Traditional array
foreach ($colors as $c)
echo "$c<br>";
// Associative array
foreach ($capitals as $state => $city)
echo("$city is the capital of $state.<br>";
- Sorting an array
sort($colors); // ("blue", "green", "red)
rsort($colors); // ("red", "green", "blue")
- Summary of array functions