A Deep Dive into PHP Arrays

A deep dive into php arrays

Arrays are one of many powerful features of PHP and for good reason. Present in nearly all modern programming languages, arrays offer a way to store types of data that can be sorted, added to, deleted from, re-arranged, and retrieved. Having this type of data structure allows us as programmers to store data during the script runtime. That's useful for many reasons and an example of this could be retrieving data from a database and iterating over it to perform a task. But what are arrays, how do you use them in PHP and how can you perform additional tasks on them, we will explore all those questions and more in this complete guide to PHP arrays.

What are PHP arrays?

An array in PHP is a type of ordered map (similar to that in C++) which is a container that stores values to keys in a particular order, all based on keys. By setting the values as other arrays, arrays can become multidimensional, arrays within arrays. As each array has keys and values, an array's keys can either be an integer for a string, whereas the array value can be of any type. Each element in an array is known as the index. By default, an array is zero-indexed. That means the index of an array starts at zero ("0"), not one ("1"). It's a common mistake when learning programming languages so don't worry if you forget or don't know! As you add more elements to the array the count of the index increases. Because elements in the array are indexed, looking up an index in an array (even large arrays) is lightning quick!

Types of Arrays in PHP

Let's start with a simple example of what an array is and how it is structured. In the below PHP array example, we're setting up an array into the variable "$test" with one item which has the key "foo" and the value "bar". Both the key and the value strings because we've cast them by wrapping them in quote marks. Arrays are used in PHP as general-purpose data storage for various types of data.

$test = array("foo" => "bar");

Among an array, there are different data structure types in PHP and ranges for various different use cases. Let's outline the different types along with a short description of what each is to help understand the key differences.


Also known as a vector, is a dynamic-sized array that is used to store and manage sequences of elements with ease.


A group of elements is known as a collection, referred to when we have any data structure that holds many items.


The stack approach is when we're looking at putting data into our structure following the LIFO (last-in-first-out) approach, used when for example you're looking to hand undo/redo operations.


Similar to a stack, in the opposite way, called a FIFO data structure (first-in-first-out). Used for example when doing task scheduling or a breadth-first search in graph algorithms.

Hash table

Finally, a hash table is an associative array for key-value pairs, great for accessing values using keys. A very popular data structure used throughout PHP, let's explore these types of arrays some more.

Associative arrays

Declaring the array in the above example is done using the long-form method. Let's explore the shorthand method (also known as short array syntax) of an array declaration. In the below example, we've achieved the same result as above but used PHP's short-form array declaration method. This can be achieved by using square brackets "[" and "]" instead of "array()". For those running legacy versions of PHP, short array syntax isn't available if using PHP versions 5.3 and below. As we've defined our example keys as strings, we can refer to this type of array as an associative array, where the keys are strings. Great for when you need to set more meaningful names to the keys instead of using numeric keys.

$test = ["foo" => "bar"];

Multidimensional arrays

We know that when creating arrays it follows the key-to-value format, and we know that the value of a key can be of the type, well anything! What if we nested an array inside another array? In doing this, the traditional array now becomes a multidimensional array. The name multidimensional means that we are now working with multiple arrays within a single array element.

$test = ["foo" => ["bar" => "123"]];

How to declare an array in PHP

We've learned the different types of arrays in PHP, but how can we declare an array ready for use in PHP? There are several ways to declare an array in PHP, so let's explore each option.

The most common, especially in early versions of PHP is declaring by using the array() function.

$numbers = array(1, 2, 3);

Same as the above, instead the syntax is different using the short array syntax.

$numbers = [1, 2, 3];

We could declare an array by setting both the keys and values. Here we're defining the specific keys to create an associative array.

$numbers = ['one' => 1, 'two' => 2, 'three' => 3];

It's possible in PHP to create an empty array to be used elsewhere. Below we've shown both the short array and normal array syntaxes for declaring an empty array in PHP.

$numbers = [];
$letters = array();

We could use PHP's built-in "range" function. The range takes two parameters, a start, and an end, allowing you to set the total number of elements in an array. This is a useful trick especially when you need random data in an array, maybe if you're testing your PHP code with PHPUnit.

$numbers = range(1, 3);

As we know it is possible to create multidimensional arrays, and declaring them in PHP is no different here. Here we've nested an array inside the parent array to create a simple example of a multidimensional array.

$numbers = [
 'numbers' => 1

What is an array index?

Every item in an array is sorted in a position, known as the index. That's what makes an array a powerful choice in PHP programming, mainly because it's data that is structured in a logical order. We've already learned that arrays are zero-indexed, so let's explore some examples of this in action.

Taking another simple array, we have three elements, which are indexed in the order they've been provided, from 0 up to index 2. If we're looking to output the value of one of the items we will need the index number. To output the word "pizza" we need to provide the variable (that's the array) the index in the brackets.

$food = ['pizza', 'burger', 'tortilla'];

echo $food[0];
# Outputs

A common error in PHP is when within the code we provide the wrong array index to an array. That normally occurs when we're asking for an element out of the array when the array doesn't contain that item. By doing this you will trigger the undefined array key error in PHP.

How to loop an array

Once you have declared an array in your code, you need to do something with it. The most common action to an array is looping its element. To take a real-world example, you might have an array of users that you wish to display to a user, one at a time. To do that you'd typically request all users from your data storage location, that's more than likely a database, then loop through each element until you're done. There are a few ways to loop an array with the most common being a for each loop. Let's explore how to loop an array with a for each.

Using the for-each loop written as "foreach" in code, allows us to pass an array to this function and loop its contents. Using a simple example below we've passed an array into the first param (a simple array with 3 numbers), and assigned each one to the variable "$number", then we're echoing each one. Using a foreach is a powerful way to interact with an array in PHP, including using nested foreach for those more complicated arrays.

foreach ([1, 2, 3] as $number) {
 echo $number . " ";

Using a foreach might not be practical for your code example, but luckily in PHP, there are other ways to loop arrays. Let's explore the different ways that are possible in PHP, with code examples.

Using a for loop in PHP is another way to loop an array in PHP, very similar to a foreach. The for loop allows you to control the total number of loops it does by using the iterator, which is "$i" in this case.

$numbers = [1, 2, 3];
for ($i = 0; $i < 3; $i++) {
 echo $numbers[$i] . " ";

You could use a while loop to loop around a PHP array, but in our example that's not the best use here, but yours might be! We're using the "count" function here to determine the total size of the array to ensure we loop the correct number of times. On a side note that "count" also has an alias "sizeof".

$numbers = [1, 2, 3];
$index = 0;

while ($index < count($numbers)) {
 echo $numbers[$index] . " ";

Using a do-while loop is also another way to loop elements in a PHP array. Similar to the while loop, but acts validating the loop statement (while).

$numbers = [1, 2, 3];
$index = 0;

do {
 echo $numbers[$index] . " ";
} while ($index < count($numbers));

The easiest to read and write is by far foreach, but it does depend on your coding requirements. It's even possible to use other array-based functions such as array_walk and array_map. PHP is a great language as it comes with many useful built-in functions, all available at your disposal. Let's explore the array-based functions in PHP.

Array-based functions in PHP

PHP comes packed full of array-based functions, which we can use in our code to achieve a handful of different things. Let's explore the most common array-based functions available to us as developers in PHP.


When working with a multi-dimensional array, use the array_column function to return the values from a single column.


If you require to check if an array contains a given key, use the array_key_exisits function to let PHP search for you.


The array_walk function in PHP is great for when you need to apply logic to each element in an array by using a callback function.


If you're looking to reset array keys in PHP then the array_values function is for you.


A great way to quickly determine if the input variable is of type array, returning true for yes, that's an array, or false, no that's not an array.

Common array errors in PHP

When working with anything in PHP, it's good to be prepared for any errors that might occur, and working with arrays is no exception to this rule. Let's explore some of the most common array errors you might face when coding PHP.

Undefined Array Key

We've covered this error in full over at your how to prevent the undefined array key error in PHP. Be sure to check that out if you've experienced this error.

Illegal offset type

This PHP error may occur when you attempt to use either an array or an object as the array key.

Array to string conversion

The most common type of PHP error when working with arrays is the array-to-string conversion error. Luckily if you've ever experienced this error we've covered this topic in our extensive guide to preventing array-to-string conversion in PHP.


Arrays in PHP are fundamental and are at the core of every website application. We've explored what arrays are, how they work, the different types, and how we can use PHP's own built functions to perform array-based tasks. By understanding the differences in data structures and when they might apply to you, including the different ways we can loop array data to obtain the information we need. Regardless of what you use arrays for in your application, we hope this guide provides you with a complete overview of how arrays work in PHP.

Senior PHP developer with near two decades of PHP experience. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Related Dev Guides

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.

Reject non-essential Accept all