In this tutorial, we’ll cover Arrays and its types which are Numeric Arrays, Multi-Dimensional Arrays and Associative Arrays.
An array is a special type of variable that is capable of storing multiple values. Numeric arrays give a numeric index to all of the values within the array. The first index of an array is always 0 and there are two ways to define them:
$myfirstarray = array(
item1 => “value1”,
item2 => “value2”,
item3 => “value3”,
$array = array(“value1”, “value2”, “value3”);
// You can also assign the index manually like this.
We access an element by referencing its
echo $dogs; // Will echo Lola.
Associative arrays are similar to numeric arrays. However, the values in the array are given named keys that you assign to them. There are two ways to create an associative arrays:
$characters = array(“Yeah”=>”19″,”Hub”=>”110″,”Website”=>”18”);
$characters[‘Yeah’] = “19”;
$characters[‘Hub’] = “110”;
$characters[‘Website’] = “18”;
// both give the same result
To access the values of this kind of array, you use the named keys instead of the usual numeric value.
A multi-dimensional array is an array that contains one or more arrays. The dimension indicates the amount of indices you would need to select an element within in.
For a two dimensional array you would need two indices to access it and for a three dimensional one you would need 3 and so on. Arrays more than 3 layers deep are very difficult to handle so I would suggest staying away from them. The arrays inside of the multi-dimensional arrays can be either numeric or associative. Let’s create a two dimensional array:
$people = array(
This two dimensional array has 3 arrays and two indices. We can think of these as a row and columns. To access this array we need to specify both the indices.
Continue to Next Chapter – Complete PHP Tutorial – Chapter 7