Skip to Content

PHP Arrays: Indexed, Associative & Multi-Dimensional

PHP arrays are a powerful asset when managing data.  There are three different array types available: indexed arrays, associative arrays, and multi-dimensional arrays.

This article covers each of these array types in detail along with some of the most widely used functions for array accessibility and manipulation.

What Is An Array?

In short, an array is a collection of data, either containing a comma-delimited list of indexed values or keys with associated values or other objects.

There are three different array types in PHP:

  • Indexed arrays: Arrays with a numeric index. The numeric index is the "key" name for each array element.
  • Associative arrays: Arrays with named keys. These names are either integer or string data types. Most other data types, like booleans, for example, will be treated as a string.
  • Multi-dimensional arrays: Arrays containing one or more arrays.

Indexed Arrays in PHP

There are a few different ways to initialize an indexed array in PHP. If you want to create an array of indexed values, you can do so like this: 

$my_array = [
"Apples",
"Oranges",
"Bananas",
"Kiwis"
];

This code creates an array containing a comma-delimited list of four different types of fruit, also known as an indexed array, and is useful any time you need to loop over a quick list of data.

You can loop through this array by using its index as the key in a for loop:

for ($i = 0; $i < sizeof($my_array); $i++) {
echo $my_array[$i];
}

// Apples
// Oranges
// Bananas
// Kiwis
You can also use the array() method to create an array in PHP. I like to stick with the shorthand syntax as it's cleaner, so we will be looking at that in the rest of the examples where applicable. Some functions don't have shorthand methods, which I'll also outline as we go along.

Associative Arrays in PHP

Another way to create an array in PHP is to assign a list of key-value pairs to each array element, also called an associative array.

An associative array in PHP becomes useful when you only want to access specific elements and data within the array:

$my_array = [
"name" => "Josh",
"title" => "Web Developer",
"website" => "orangeable.com"
];

echo $my_array["website"];
// orangeable.com

However, you can still loop through each of the key-value pairs if you need:

foreach ($my_array as $key => $value) {
echo $key . ' = ' . $value;
}

// name = Josh
// title = Web Developer
// website = orangeable.com

Multi-dimensional Arrays in PHP

A multi-dimensional array in PHP is an array containing one or more arrays within a single array:

$my_array = [
[1, 2],
[3, 4]
];

for ($i = 0; $i < sizeof($my_array); $i++) {
for ($j = 0; $j < sizeof($my_array[$i]); $j++) {
echo $my_array[$i][$j] . '<br/>';
}
}

// 1
// 2
// 3
// 4

Here, We're creating a multi-dimensional array $my_array. The first element contains an additional array with values 1 and 2, while the second element contains an array with values 3 and 4.

Now let's say you have a multi-dimensional array with a set of key-value pairs:

$my_array = [
"key1" => [
"key1a" => "value1",
"key1b" => "value2"
],
"key2" => [
"key2a" => "value1",
"key2b" => "value2"
]
];

You can't loop through each step by step the same way. For this example, we need to use a foreach() loop:

foreach ($my_array as $key => $value) {
var_dump($key);
var_dump($value);
}

And now the output becomes:

// key1
// {["key1a"]=>"value1", ["key1b"]=>"value2"}
// key2
// {["key2a"]=>"value1", ["key2b"]=>"value2"}

You could also access specific values within this array by any of its key names:

echo $my_array["key1"]["key1a"];
// value1
With PHP, you can go as many levels deep as you need in your arrays. Try to keep multi-dimensional arrays in PHP as simple as possible. Although possible, any multi-dimensional arrays that are more than three levels deep tend to get confusing and unmanageable for most people.

Array Data Types

With PHP arrays, you can store different types of data as the array values. Here are some examples of this.

Create an array with a mixture of integer, floating point, string, and boolean values:

$my_array = [
1,
2.0,
"Element 3",
true
];

Each array value's data types are retained for use as needed within your application.

If you loop through the data and output each of the values one by one, you'll get this result:

for ($i = 0; $i < sizeof($my_array); $i++) {
echo $my_array[$i];
}

// 1
// 2.0
// "Element 3"
// true

Getting the Size of an Array

There are two available functions for testing the size of an array. By size, I mean the number of elements within an array:

$my_array = [
"Apples",
"Oranges",
"Bananas",
"Kiwis"
];

echo sizeof($my_array);
echo count($my_array);

Both sizeof() and count() methods return the same result: 4.

Appending Data to an Array with array_push()

A lot of times, you won't know the data you need to add to your array offhand. A practical example could be converting a resultset from a database into an array and loop over it.

For this example, we'll stick with something simple by creating an array with five values, 1 - 5:

$my_array = array();

for ($i = 1; $i <= 5; $i++) {
array_push($my_array, $i);
}

Or the shorthand method:

$my_array = [];

for ($i = 1; $i <= 5; $i++) {
$my_array[] = $i;
}

Both create an array with the same data:

[1, 2, 3, 4, 5]

Remove an Array's Last Element with array_pop()

Alternatively, you can remove the first element from the array using the array_shift() method:

$my_array = [1, 2, 3, 4, 5];
array_pop($my_array);

var_dump($my_array);
// [1, 2, 3, 4]

Prepending Data to an Array with array_unshift()

Just like appending data to an array, you can also prepend data to an array with the array_unshift() method.

To prepend simply means adding new data to the front of the array instead of the back:

$my_array = [1, 2, 3, 4, 5];
array_unshift($my_array, 6);

var_dump($my_array);
// [6, 1, 2, 3, 4, 5]

I don't believe there is a shorthand method for prepending array data like there is with appending array data. If you know of any shorthand methods for this, let me know.

Remove an Array's First Element with array_shift()

Alternatively, you can remove the first element from the array using the array_shift() method:

$my_array = [1, 2, 3, 4, 5];
array_shift($my_array);

var_dump($my_array);
// [2, 3, 4, 5]

Remove an Element from any Array with array_splice()

You can remove an element or multiple elements from an array by using the array_splice() method.

This example removes all elements from array index 2 and on until it reaches the end:

$my_array = [1, 2, 3, 4, 5];
array_splice($my_array, 2);

var_dump($my_array);
// [1, 2]

If you only wanted to remove the value from array index 2, you can also provide a length attribute of 1 as the method's third argument, which will show the following output:

$my_array = [1, 2, 3, 4, 5];
array_splice($my_array, 2, 1);

var_dump($my_array);
// [1, 2, 4, 5]
Remember that in PHP, the array index starts at 0 and not 1. So if you pass an index value of 2 like we did in the previous example, you're actually removing the third element from the array. Just remember that array positioning is by the index value which always starts at 0.

Conclusion

PHP comes packed with tons of functionality for arrays. You can create indexed arrays, associative arrays with key-value pairs, and multi-dimensional arrays in PHP with (close to) endless possibilities.

Many of these array functions have been supported since PHP 4 so, unless you haven't updated your local machine or server in over 20 years, you should be in good hands.

There are many many many additional array functions in PHP that we could cover. This article covers the basics to get you started with arrays in PHP.

Posted by: Josh Rowe
Created: December 16, 2020

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.