What is an array? Arrays are common to almost every programming language. An array is simply an ordered map of values, indexed so you can find these values, called elements. These elements can be of multiple datatypes, and can be ordered any way you want.
1 2 3 4 5 6
Two types of arrays in PHP
Associative arrays allow you to index each element with an arbitrary value. For example, you can use letters of the alphabet, or just about anything to index the value, as long as it’s unique. Here is an example:
1 2 3 4 5 6
Some programmers prefer associative arrays because they can use the key to indicate what type of data is stored in the element, like “name” in the above example. This is an indicator of what is stored, however its not a rule that’s enforced. You can just as easily put a phone number in a name field and vice versa.
Enumerative arrays are indexed with a numerical index, either auto incremented, or random. PHP is very flexible with arrays, you can use numbers at will, and add in associative elements, and return to enumerative again. Also, the keys do not need to be sequential. Also note if you leave a key blank, an auto incremented number will be assigned to the key. Here is an example of an enumerative array:
1 2 3 4 5 6
How to build an array in PHP
Using the array function you can create arrays a few different ways:
1 2 3
What do we do with arrays?
There are a few neat things we can do with arrays. You can extract only specific parts of an array:
or you can loop through an array:
1 2 3 4 5 6 7
There are many things arrays can be really handy for, and I’ll cover that in future articles.
Checking your arrays
One question you might have is, how to easily check the data in the array. There are two easy ways to do this.
This will display the contents of your array so you can visually verify the data before processing it. Print_r will recursively print the values of your elements. Here is another way:
This also prints out the values of your elements, but displays the datatypes as well. Whether or not you need this functionality will determine whether you use print_r or var_dump.
Arrays are a beautiful thing. Mastering them is key to success in any language. In future articles I will cover some of the things you can do with arrays.
Questions or comments? Contact me!