|
|
Arrays
What Are Arrays?
Normal variables can store only one value - for example, a single number, or a string. An array is a special variable which can store several values, allowing them to be accessed easily with a numerical or text index.
Basic Arrays
In the most basic array, each element, or value, has a sequential numeric index. PHP provides an array() function, which can be used to create an array:
$myArray = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
This creates an array, $myArray, with 7 string elements. The elements can be accessed using their index as follows:
echo($myArray[0]); //Sunday
echo($myArray[1]); //Monday
echo($myArray[2]); //Tuesday
// ...
There are three more ways to assign values to numerical arrays. We can specify the indices explicitly using the array() function:
$myArray = array(0=>"Sunday", 1=>"Monday", 2=>"Tuesday", 3=>"Wednesday", 4=>"Thursday", 5=>"Friday", 6=>"Saturday");
Or, we can create the array elements individually:
$myArray[] = "Sunday";
$myArray[] = "Monday";
$myArray[] = "Tuesday";
// ...
$myArray[] = "Saturday";
Having not specified an index for each element as we create it, PHP will automatically assign the value to the next unused index in sequence, starting with 0.
Associative Arrays
Often, it is useful to use a string as the index, rather than a number. This is called an associative array. The same syntax as above can be used to create associative arrays:
//Using the array() function:
$myFamily = ("mum"=>"Jane", "dad"=>"James", "grandma"=>"Josephine", "grandad"=>"John");
//Assigning elements individually:
$myFamily["mum"] = "Jane";
$myFamily["dad"] = "James";
$myFamily["grandma"] = "Josephine";
$myFamily["grandad"] = "John";
Page Responses
Currently there have been no responses to this page...
If you have anything to contribute to this tutorial, found a bug, or know a better way of achieving the same goal, please leave your response below.
|