Introduction to the PHP array
One of the fundamentals of programming is the
array type which when it comes to PHP can have some variation in structure. Most commonly is the numerically indexed
array and the associative
array, both of which can be multi-dimensional if required. Array’s are responsible for holding structured data, to be utilized throughout your application in a range of circumstances.
As the writers on PHP docs describe it –
“An array in PHP is actually an ordered map. A map is a type that associates values to keys.”
Reference: PHP Arrays Documentation
In general, a PHP
array can have any type of value, which gives a huge range of diversity. But the key (which is essentially an index or string identifier that is mapped to the value), on the other hand, can only be an
integer or a
string. Apart from objects, key’s of which aren’t of these two types will be automatically cast to either an
integer or a
PHP arrays are vastly flexible in the sense that you can have a mixed key structure, this is where values have integer keys and string keys. I know, that sounds strange but I imagine it has its uses!
I know there are many articles out there guiding learners through the syntax of PHP arrays. But what I want to do is allow you not only to learn the syntax but to visualize the
array too. Being able to visualize an
array in the mind serves a world of difference to any developer. Both on the development side and on the debugging side.
But not just this, it’s worth exploring some of the key characteristics of the PHP
array type that will give some insight into how it works. So let’s have a look at a general view of PHP
PHP Array Characteristics
Arrays in PHP come in three ‘styles’, these styles are commonly identified as indexed, associative, and multidimensional. Here’s what these styles represent in a nutshell.
- Indexed – an
arraythat has keys that are of
integertypes. For example, each value will be mapped to a numeric index starting from 0.
- Associative – An associative
arrayhas values that are mapped to keys that are of a
stringtype, this can essentially be any string, it could be named “MySuperWeirdKeyName”.
- Multidimensional – An array that holds further arrays as its values and so on.
Across all of the different styles of arrays (indexed, associative, multidimensional) there are some general common principles on how they function. Let’s break them down
- They store keys and values just like any other programming language.
- Although we have different styles of arrays in PHP (indexed/associative/multidimensional), PHP doesn’t actually differentiate between the two. It’s essentially only us humans that do!
- PHP Arrays can have mixed keys, meaning that you can have a value mapped to the
integer1 and another value mapped to a string named “one”, all in the same array! You can see this demonstrated in the advanced example here.
- Keys can be only of two types,
string, but values can be of any type.
- There are two ways you can create an
arraysince PHP 5.4, one is by using
array(1,2,3,4)and the other by using
[1,2,3,4]– We will see more on this later.
arrayin PHP is somewhat different to other languages such as C# or Java. It doesn’t have accessible properties from the
arraytype itself and therefore depends on other functions to get these properties such as the length of the array (the number of elements in the uppermost level of the array). A quick way of explaining this is in PHP, to get the count of an
arrayyou would have to use
count($arrayVariable)where in Java, you would use the
arrayVariable.lengthsyntax. PHP has many of these functions that help with getting properties or interacting with the array.
- PHP arrays can nest further arrays inside them, morphing into a multidimensional array.
arraysare a breeze to use, populating or depopulating data can be done in a variety of ways, some of which is the commonly known push, pop methods.
- They can also be iterated over in a range of ways too which can be seen in an article I wrote about the various ways you can loop over an array in PHP.
- There is no maximum limit to the size of an
arrayin PHP. This essentially allows as many elements as possible until the memory maxes out!
My apologies if the above points are a bit of information overload, but the insight is necessary to understand the true flexibility.
In the following contents, the numerically indexed, associative, and multidimensional arrays will be explored. Some of which will be in basic form and some that are of a more advanced state.
Before we start, as previously stated, there are two ways of creating and
The first is for any PHP Version (which is essentially the old style)
$myArray = array();
The second is for PHP Version 5.4+
$myArray = ;
In the following examples, the later style syntax has been used.
Note: If you’re following this tutorial hands-on and have an earlier version to 5.4, you will have to utilize the earlier syntax style.
Now to get our hands messy with some
array syntax and visualize the virtual contents of an
Numerically Indexed Arrays
Numerically Indexed Example 1
The first example is fairly straight forward, pushing in integer values, nothing to fancy.
$mySimpleArray = [1,2,3,4];
When we print this
array, we can see that keys have automatically been mapped to the values in incrementing order.
Let’s explain the above screenshot.
- As you can see, almost by magic, on the left-hand side, the numbers 0,1,2 and 3 have appeared. This is because PHP has automatically created keys and mapped them to the values on the right.
- These numeric indexes always start from the point of zero and increment upwards.
Numerically Indexed Example 2
Let’s try a mixed type array
$myArray = [1,"two",true,false];
As we discussed earlier, the values of a PHP
array can be of any type, the output visual of this
array shows that this is true.
Accessing values from the array
With a numerically indexed
array we can access the values by their corresponding index. For example, let’s get the value of “two”.
echo $myArray; // outputs two
In the following examples, some slightly different syntax is used to assign keys to values within the
Have a look at the below diagram to understand what the syntax is doing.
Associative Arrays Example 1
With an associative
array we can define the keys by a string value. Giving some identifying name to each value. This is especially good for usage with database query results because the associative key can be the corresponding column name.
$myArray = ["myAssociativeKey1" => "myValue1", "myAssociativeKey2" => "myValue2"];
As we can see in the output, we have mapped our own custom keys to the values, and the variable is created.
Associative Arrays Example 2
Because PHP doesn’t consider an associative or numerically indexed
array a different type, we can do exactly the same thing as we did earlier. Let’s create a mixed value type of associative
$myArray = ["myAssociativeKey1" => "myValue1", "myAssociativeKey2" => 1, "myAssociativeKey3" => false, "myAssociativeKey4" => true];
Accessing values from the array
Now that we are using associative keys, let’s grab the value of ‘myValue1’
echo $myArray["myAssociativeKey1"] // outputs myValue1
This is where arrays get a fairly more complex, nesting comes into play and so an
array can hold another
array of values making it a multidimensional
Multidimensional Indexed Example 1
In the first example, we use an associative key with an
array as it’s value.
$myMultidimensionalArray = [ "dimension1" => ["myKey" => "myValue"] ];
As we can see from the output, the key ‘dimension1’ as a value of another
array which subsequently holds it’s own key and values.
Multidimensional Indexed Example 2
In this example we throw all of the preceding examples together, showing the true flexibility of the multidimensional style in PHP. It will include associative key and values, numerically indexed and values and dimensions with nested arrays.
$myMultidimensionalArray = [ "myKey1" => "myValue", 2, "dimension1" => ["myKey1" => "myValue1"], "dimension2" => [1, 2, 3, 4, 5], "dimension3" => ["mySubDimension" => ["mySubSubDimension" => [5, 6, 7, 8], 2, 3, 4]], true, false, ];
As you’ll probably agree, it looks extremely messy but, of course, it’s showing its true flexibility. Being able to be numerically indexed, associative, and having multiple dimensions at the same time.
Accessing values from the array
With this more diverse
array, we need to be careful that we use the exact keys in the right order. Let’s print the array nested inside with the key of ‘mySubSubArray’.
print_r($myMultidimensionalArray["dimension3"]["mySubDimension"]["mySubSubDimension"]); // outputs Array (  => 5  => 6  => 7  => 8 )
Let’s put the syntax explored in this article into a real-life data scenario.
The first example is an associative
array with a list of shopping items for two people in the style of a numerically indexed
Real-life example 1
$shoppingListArray = [ "MikesShoppingList" => ["Beer", "Apples", "Pasta", "Beef"], "DansShoppingList" => ["Meatballs", "Chicken", "Cheese", "Pears"] ];
Accessing the values
Again, we could quickly access the contents of ‘DansShoppingList’ with the following syntax.
print_r($shoppingListArray["DansShoppingList"]); // outputs Array (  => Meatballs  => Chicken  => Cheese  => Pears )
Or we could access the actual items on the list directly like the following
echo $shoppingListArray["MikesShoppingList"]; // Outputs Beer echo $shoppingListArray["DansShoppingList"]; // Outputs Cheese
Real-life example 2
Another example could be the contents of a user’s tweet on Twitter. Check out the following data which is exclusively an associative
$twitterTweet = [ "user" => "@DanEnglishby", "tweet" => "Hey Devs, What's up?", "timestamp" => date('Y-m-d H:i:s'), "retweet_count" => 6, "favourite_count" => 9 ];
Accessing the values
array is all associative, we can access the relevant values with the following syntax –
echo $twitterTweet["user"]; // Outputs @DanEnglishby echo $twitterTweet["tweet"]; // Outputs Hey Devs, What's up?
I hope this explainer helps you understand the traits of PHP’s style of arrays. As explored, they have the utmost flexibility. Being able to hold any types as values, multiple key types, and the ability to nest and nest, potentially producing humongous multidimensional arrays.
This article also shows the flexibility of accessing or getting values from an
array too. Whether it be by using integer indexes or associative string keys.
If you’re interested in learning more about PHP arrays, here are some articles I’ve written in the past –