An array is a type of variable that may contain several values at once.
There are three types of arrays, namely:
- Indexed array - An array with a numeric key
- Associative array — An array where each key has its own specific value
- Multidimensional array — An array containing one or more arrays within itself
Indexed Arrays
An indexed array stores each array element with a numeric index. Below are examples of creating indexed arrays.
<?php
// Define an indexed array
$cities = array("New York", "Salt Lake", "Tokyo");
var_dump($cities);
Arrays can also be created manually:
<?php
$cities[0] = "New York";
$cities[1] = "Salt Lake";
$cities[2] = "Tokyo";
var_dump($cities);
Looping through indexed arrays can be done as follows:
<?php
$cities = array("New York", "Salt Lake", "Tokyo");
$arrlength = count($cities);
for($i = 0; $i < $arrlength; $i++) {
echo $cities[$i];
echo "<br>";
}
Associative Arrays
Associative arrays are arrays that use named keys that are assigned by the user.
An associative array can be created by:
<?php
// Define an associative array
$ages = array("Mark" => 22, "Jeff" => 32, "Mike" => 28);
var_dump($ages);
which is equivalent to:
<?php
$ages["Mark"] = "22";
$ages["Jeff"] = "32";
$ages["Mike"] = "28";
var_dump($ages);
Looping through an associative array can be done using a foreach
loop.
<?php
$ages = array("Mark" => 22, "Jeff" => 32, "Mike" => 28);
foreach($ages as $x => $x_value) {
echo "Name = " . $x . ", Age = " . $x_value;
echo "<br>";
}
Multidimensional Arrays
A multidimensional array is an array in which each element may also be an array, and each element in the sub-array can also be an array or have another array within it, and so on.
Below is an example of a multidimensional array.
<?php
// Define a multidimensional array
$friends = array(
array(
"name" => "Mark",
"country" => "USA",
),
array(
"name" => "Jeff",
"country" => "Japan",
),
array(
"name" => "Raymond",
"country" => "United Kingdom",
)
);
// Access nested value
echo "Raymond is from " . $friends[2]["country"] . ".";