What Are PHP Arrays?

php arrays

Arrays are common not only in PHP, but in any programming language you will come across. Arrays are very useful since they allow us to group together information in a very organized way. At it’s core, an array is a collection of different pieces of information or data which is ordered and indexed via integers. The information gets stored in specific index positions which makes it convenient to insert into and remove out of each pocket or index so to speak. An array can hold pretty much whatever you want to put into it, whether that is a string, number, integer, floating point values, another array, or an object. We’ll be using arrays more and more moving forward so let’s dig right into the nitty gritty with PHP Arrays now!


Creating an Array in PHP

With those beginning thoughts in mind concerning arrays, let’s create one and put some information in it. In this example, let’s imagine we want to have just one variable that contains a collection of house styles. We can do this by creating an array, populating said array with the styles we want, then assigning that array to the variable. This is how we might do this:

Just like that we have an array which is now stored in the $houses variable. Great, so how do we get information out of our array now? Well, lets try to echo out the information in that array like we have been doing with all of the other variable types up until now.

Notice: Array to string conversion in C:wampwwwphpconsoleindex.php(61) : eval()’d code on line 3
Array

Hmm. Not great. When we tried to echo out the information in our variable, it gave us a warning. It did tell us however that the variable contains an array. There is a different notation for working with arrays when we’d like to retrieve information out of them. We need to specify the index we are interested in using the square brackets notation like so []. You’ll need to keep in mind that arrays are zero based. That means with arrays you don’t begin counting from 1, you count starting at 0. So in our example we populated our array with f different styles of houses. This means we need to look in index [0], [1], [2], and [3]. Notice how we use the square brackets to enclose the index we want to get access to. Let’s try it out in our testing ground:

Colonial
Contemporary
Southwestern
Metro

Nice! Now we’re seeing how to grab the info out of the variable. So at index zero we have our Colonial, index 1 has a Contemporary, index 2 Southwestern, and index 3 has a Metro. With arrays you can store as many values as you need to, maybe you have 500 emails you want to store in a variable, with an array you can do that no problem.

Mixed Values in Arrays

When you have an array, you are not limited to the types that you can store in it. Just above we put a handful of strings into the $houses variable. Now, we can set up variable that is a bit more dynamic. Let’s see how.

7
House
Car

Excellent. First, we assigned a bunch of values to our new dynamic array. At index 0 we placed a number in, specifically an integer. At index 1 is a string. Index 2 is also a string. Note that in the third index is an array. Well how about that America, an array within an array. Yes You Can! Consider this an introduction to multi-dimensional arrays. Having an array within an array requires us to put on our thinking cap. We saw how to get at the data contained in simple array, now how do we deal with this type of thing. Let’s see.

7
House
Car
grass
mower
mulch

Fantastic! When there is an array within an array, you need to level up partner. That is, you need to get to the next level. Notice how we use the double bracket notation to dig deeper into that array within an array [][]. What is this doing for us? Well you see, in the first bracket, we need to specify where we want to look. In this case we want to look at position 3 since that is where the second array lives which we want to peer into. Ok, great – now just repeat the process. Now that you’ve specified the third position of the first array, what position of the second array do you want to access? Put this value in the second bracket. This is how you access arrays inside of arrays and this is what you call a multi dimensional array. You are not limited to only two levels either. You can have arrays within arrays within arrays, however you will begin to drive yourself mad if you nest these things to excess. A good rule of thumb is to try and mimic real data configurations that you might find in the real world. Just for kicks though, let’s put one more array within an array to test it out.

7
House
Car

grass
John Deere
Kubota
New Holland
mulch

Excellent. See how now that there is an array inside an array inside an array, we just use triple bracket notation [][][] to get at that data. Is there really a need to go this many levels deep? Not a lot, but it does help to know how this stuff clicks together, much like our beloved sophisticated interlocking brick system (Legos).

Look Deep Into The Array

When faced with the task of looking deep into the abyss an array, you can make use of the ever useful print_r() function to see how the array is structured. It makes data inside of an array much easier to read. In addition to using the print_r() function, it helps to wrap the output within html pre tags. Let’s see how this works.

Array ( [0] => 7 [1] => House [2] => Car [3] => Array ( [0] => grass [1] => Array ( [0] => John Deere [1] => Kubota [2] => New Holland ) [2] => mulch ) )

Notice here that we use the print_r() function a couple of times. The difference is that the second time, we wrap the output in html pre tags. The pre tags provide a nice formatted output so that it is easier to see how things nest within the array. See how each time we reach another array, the output is indented to give us a visual indication that something interesting is happening here. Put that print_r() function in your back pocket, you’re going to use it all the time when debugging your code. There is one thing to be aware of when retrieving data out of your arrays, and that is you need to specify an index that actually exists or you’ll get an error.

Notice: Undefined offset: 4 in C:wampwwwphpconsoleindex.php(61) : eval()’d code on line 3

You see we get an undefined offset error if we specify to retrieve data from an index that does not exist. So it seems we’d like to get data out of index 4 but there is nothing there, well let’s add some data into that pocket, it’s easy enough to do, check it out.

Bike

By simply assigning a new value to the variable $dynamic[] using the bracket notation, PHP knows that you want to add something to the end of the array. Note that you didn’t even have to indicate that it was position 4 where you wanted to place something, it just did it for you. Just to bring the idea home, let’s look at one more example.

This is a neat example here. See how we can easily overwrite and existing index by simply assigning a new value to it. This is why index 1 no longer has a House in it, but a Big House in it. Suppose that you need to add something at a specific position, we did that as well. Note that index 9 now has a Surf Board in it.


Associative Arrays

We’re getting a good handle on arrays in PHP, but we’re not done yet. So far we have been working with plain old vanilla index based arrays. The standard index based array relies on numeric keys to work with them. The keys are often invisible to us until we actually output the full array using a pretty print. Associative arrays are a little different in that the keys must be specified explicitly using a label of some type. Think of it like a collection of file folders with labels on them. The label on the folder is the key, while the contents located inside of the folder is the value. The easiest way to see how this works is to simply look at some code.



Nice Work! We have turned our formerly boring standard array into a fully associative array. Now we can access this data using named keys of some type instead of only numeric indices. To be fair, all we did was a pretty print of the contents so let’s look at the actual syntax we would need to use to access all of this information.

7
House
Car
grass
John Deere
Kubota
New Holland
mulch

Slick! See how instead of putting the number of the index in between the brackets, we now put in the label, whatever that may be. Note that for arrays within arrays, you might need to use a combination of index based and associative labels to get at the data you are looking for just like we did above.

Wrapping Up

We have the basics of PHP arrays covered. Use this and other examples to refine your skills. Soon we will dig into all of the amazing functions for dealing with arrays that PHP provides to us, and there are many!