It's time for my favourite data type. I absolutely love arrays! They are fantastically fun, and really useful. Arrays are great for when one value isn't enough, and for some reason the collection of values are related.
Indexed
Let's say that we want to store the names of all of our pandas within our application. They are all pandas. They are related. It doesn't make sense to create separate variables for each of them.
Let's store them in an array, shall we? What?! Don't tell me you didn't see that coming. You saw the title, didn't you?
<?php
// Create an array.
$pandas = array('Lushui', 'Jasmina', 'Pali');
// Create an array as well.
$pandas = ['Lushui', 'Jasmina', 'Pali'];
Here we have two examples of arrays. They both work out the same, but the second example was a syntax that was added in PHP version 5.4. This means that it won't work on versions before 5.4. However, I highly recommend using the second format, since the PHP world is moving forward, and we'll soon all be using version 5.6.
Some people like to use the first type of array in code that they intend to share with others, so that it remains compatible with all versions of PHP. We'll be using the new array syntax for most of the examples in this book. You're free to use the older ones if you choose to do so.
Array values are held between either an array(
and a )
or between an [
and a ]
(square brackets). Each element of an array must be separated by a comma: ,
. The last option in an array can also take an optional comma, but I prefer to leave it out. In the example above, we've added three string values to an array. Arrays can hold strings, other data types, or even other variables!
Here are some more examples.
<?php
// Create an array of strings.
$pandas = array('Lushui', 'Jasmina', 'Pali');
// Create an array of integers.
$integers = [3, 6, 9, 12];
// Create an array of floats.
$floats = [1.30, 2.60, 3.90, 4.120];
// Set some variables.
$one = 1;
$two = 2;
$three = 3;
// Create an array of variables.
$variables = array($one, $two, $three);
Arrays are extremely flexible too. They can hold a mix of different types of values. Here's another example.
<?php
$one = 1;
// Create an array of mixed values.
$mixed = array('Lushui', $one, 5, 23.54);
Great! They're extremely flexible, but how can we use them? We want to be able to retrieve these values that we've collected together, right? Don't worry, we can get to them!
Let's assume that we're working with the first example. Here it is once again to refresh your memory.
<?php
// Create an array of pandas.
$pandas = ['Lushui', 'Jasmina', 'Pali'];
Let's try to access 'Lushui'. This is an indexed array so we can access each individual element by their position in the array. Lushui is the first item, so let's go ahead and attempt to access it.
<?php
// Create an array of pandas.
$pandas = ['Lushui', 'Jasmina', 'Pali'];
// Get the first item from the array.
$lushui = $pandas[1];
// Echo the result.
echo $lushui;
We can access our array items by using square brackets at the end of the array variable and providing an integer value for position between them. Let's go ahead and run the code. I'm eager to meet Lushui!
Jasmina
Wait, what!? Jasmina? Well, I can't be mad at Jasmina. She's a beautiful red panda that belongs at Bristol zoo, but I was expecting Lushui! Why are we graced with Jasmina's presence? It's because we're programmers.
Actually, I'm still learning.
Shh you! You've got this far, and you haven't quit on me. You're practically a programmer already.
Here's a secret. Programmers count from zero. That means that position 1
is in fact the second element in our array. This is why Jasmina is chewing on our trouser legs.
Let's fetch Lushui using position zero so that Jasmina has someone to play with!
<?php
// Create an of pandas.
$pandas = ['Lushui', 'Jasmina', 'Pali'];
// Get the first item from the array.
$lushui = $pandas[0];
// Echo the result.
echo $lushui;
Now, with a little bit of luck...
Lushui
Hurray! Here's our lovely little Lushui.
We can provide any index that we want to retrieve our pandas from the array. Here's another example.
<?php
// Create an of pandas.
$pandas = ['Lushui', 'Jasmina', 'Pali'];
// Fetch our pandas into separate variables.
$lushui = $pandas[0];
$jasmina = $pandas[1];
$pali = $pandas[2];
Let's see what happens if we try to retrieve value 3
from the array. Since our arrays are zero-based, that means that nothing should exist at position three, right? Let's find out. First we'll need a snippet to test.
<?php
// Create an of pandas.
$pandas = ['Lushui', 'Jasmina', 'Pali'];
// Fetch a panda that doesn't exist.
$fakePanda = $pandas[3];
// Dump the result.
echo $fakePanda;
There, that should do the trick! Right then, let's execute the code and see what happens.
PHP Notice: Undefined offset: 3 in <FILENAME> on line 7
Oh dear! We've got a notice. It's not quite an error, but it's not what we want. When you've learned about functions you'll be able to count the number of elements in an array which will help to avoid this error. For now, you'll have to be careful!
It's time to take a look at another type of array.
Associative
Associative arrays are ones with user defined keys. In some languages, these are known as maps, hashes or dictionaries. In the previous section the keys to our arrays were integers that were provided automatically. Why don't we try providing our own? Let's try to have a little more control over our arrays.
The keys for our our associative arrays must be strings. So let's create a map of number names to their integer values.
<?php
// Create an associative array.
$numbers = [
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6
];
Our array keys and values are separated by an equals =
and greater-than >
symbol stuck together. We call this the array assignment operator. The keys can be found on the left, and the values on the right. Otherwise, the array takes a similar format to an indexed one.
Let's try and retrieve the value at position zero.
<?php
// Create an associative array.
$numbers = [
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6
];
// Dump a value.
echo $numbers[0];
Let's go ahead and run our file again.
PHP Notice: Undefined offset: 0 in <FILENAME> on line 14
Oh no! There's that error again. Wait, I know! It's because we provided our own keys. PHP didn't have to provide numeric keys for us, so using integer values isn't going to work. Let's try using one of our keys to retrieve a value instead.
<?php
// Create an associative array.
$numbers = [
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6
];
// Dump a value.
echo $numbers['three'];
Let's try running our application again. Fingers crossed.
3
Great! That's just what we wanted. Now we've learned how we can create our own keys to make our arrays more manageable. There's one final trick to arrays that I'd like to share with you.
Multi-dimensional
Now, we know that red pandas are multi-dimensional. They open portals through the fabric of space and time to travel to people who need cuteness and happiness. They also use these portals to travel to areas with vast quantities of fresh fruit, so they aren't entirely selfless. Well as it turns out, arrays can also be multi-dimensional.
Remember when I told you that arrays can hold any data type? Well it turns out that arrays are a data type. Can you think of any reason why an array shouldn't be able to hold other arrays? No? Well neither can I. Let's try it.
<?php
// Create a multi-dimensional array.
$numbers = [
'prime' => [2, 3, 5, 7, 11],
'fibonacci' => [1, 1, 2, 3, 5],
'triangular' => [1, 3, 6, 10, 15]
];
Here we have a multi dimensional array of popular mathematical patterns. The outer array is associative, with keys representing the pattern names. The internal arrays are indexed ones. They could be associative as well if we had wanted. I just thought that this might keep it simple.
We can use a concept of 'depth' to describe an array of this kind. This array is two layers deep. It has an outer layer (the associative array) and and several secondary layers (the indexed arrays). Arrays can be as deep as we like, once again I've kept it to two layers for the sake of simplicity.
If we wanted to retrieve the third value from the Prime sequence array, we've discovered that we can use a snippet similar to the following.
<?php
// Create a multi-dimensional array.
$numbers = [
'prime' => [2, 3, 5, 7, 11],
'fibonacci' => [1, 1, 2, 3, 5],
'triangular' => [1, 3, 6, 10, 15]
];
// First get the prime numbers array.
$primes = $numbers['prime'];
// Next get the third (second, zero-based) number.
echo $primes[2];
Of course, we receive the value '5'.
We know that this works, but I've got a better way. We can shorten this. Shall I share it with you? Well, I suppose that you have bought the book, so that means we have a legally binding contract, right? I have to share with you. Fine! Let me explain through the medium of interpretive dance. Actually, hold on. A code snippet might make more sense.
<?php
// Create a multi-dimensional array.
$numbers = [
'prime' => [2, 3, 5, 7, 11],
'fibonacci' => [1, 1, 2, 3, 5],
'triangular' => [1, 3, 6, 10, 15]
];
// Access our prime number directly.
echo $numbers['prime'][2];
Using additional sets of brackets, we can step deeper into our multi-dimensional array to access nested values directly. We can provide as many sets of brackets as we need to. We can even mix numeric and string based keys.
It's worth noting that if any of the indexes in the chain are missing we will receive our old friend the 'Undefined index' notice.
Multi-dimensional arrays are a great way of expressing grid based data, or even 2D/3D coordinates. Most of the time, however, they are simply used to express complex data structures.
In the next chapter, we'll take a look at how we can cast the values into different data types.
My books are available online for free to encourage learning. However, if you'd like for me to keep writing, then please consider buying a digital copy over at Leanpub.com.
It's available in PDF, ePub, and Kindle format, and contains a bunch of extras that you won't find on the site. I have a full-time job, and I write my books in my spare time. Please consider buying a copy so that I can continue to write new books from the comfort of my sofa!