In our previous post we’ve seen that values can be stored in variables. But what if you want to group a set of variables into 1 variable. For this case we can use an array.
You can see an array as something like you filesystem (Windows Explorer or Mac Finder). It has a top-level folder and can nest various subitems. For instance you can have an array with categories in 1 single variable called $categories. We would set it up like this:
<?php$categories = array('my first category', 'another one', 'etc');?>In the example above we add 3 categories to the $categories variable we can get the category values by utilizing the code below:
<?phpecho "My first category is " . $categories[0]?>As you can see we added the variable with a zero in square brackets. Items in an array will by default start to count at 0. These numbers can be a bit confusing and therefor we can also use names when we create an array. Let’s see how that works:
<?php$categories = array( 'first' => 'my first category', 'second' => 'new category', 'third' => 'etc...') // Show the second categoryecho "The second category is " . $categories['second'];?>As you can see we assign a name to the value, these are called key-value pairs. You can now access the value within the array using this key.
In a later course we will look how to loop through the array when we do not know how many keys there are.
Nested arrays
Now we have mastered how we can use arrays we can also have a look at another powerful feature which is nesting. Actually it is nothing more than putting an array in an array. The code below will probably make it all clear.
<?php$shop = array( 'electronics' => array( 'stereo set', 'speakers' 'tv' ), 'software' => array( 'games', 'office', 'graphics' )); echo "I want to buy a " . $shop['electronics'][0];?>As we can see we have used associative and non-associative arrays here. We access the top level array by adding ‘electronics’ and get the first element within electronics by giving it a key 0.
Try and play some with arrays because they will be very commonly used in your future projects.