You always need to store data in your app – variables are used to store data values. An array is a specific type of variable that can hold multiple values – all under the same variable name. Developers then retrieve a value by referring to it by a text key or indeed an index number in that array.
PHP is the language behind WordPress, and it frequently uses arrays. So when you develop for WordPress or even just use WordPress you are likely to come across arrays – just looking a the core WordPress code will highlight arrays, while you will also see arrays in plugins and themes.
The array() function is used in PHP to create an array. There are three types of arrays in PHP:
- Indexed, where you use a numeric key to access individual values in an array
- Associative, where strings or unique text is used to find the value in an array
- Multidimensional, where a single array in fact contains a number of other arrays
A common way to use an array is to “loop” through the entire set of values in the array and to modify each of these values in some way. As an example, if you have a few pieces of fresh fruit you can store the names of the fruit using a new variable for each fruit, like this:
$myfruits1 = "orange";
$myfruits2 = "peach";
$myfruits3 = "banana";
Alternatively, you can use an array – because using unique variables for each piece of fruit can cause a mess. Programmers would be inclined to use an array that looks like this example:
$myfruits = array("orange", "peach", "banana");
With that array you can use various functions to manipulate the array, performing specific operations on an entire data set all in one go. One example is count() – this function will tell you how many items there are in your array. You can also find a specific value – $fruit will return the word “banana”. Remember that in indexed arrays the first array item is number 0.