1. Code
  2. Coding Fundamentals

Understand Arrays in PHP

In this post, you'll learn the basics of arrays in PHP. You'll learn how to create an array and how to use associative and multidimensional arrays, and you'll see lots of examples of arrays in action.
Scroll to top

In this post, you'll learn the basics of what is an array in PHP. You'll learn how to create an array and how to use associative and multidimensional arrays, and you'll see lots of examples of arrays values with PHP in action. 

What Is an Array in PHP?

In PHP, an array is a data structure which allows you to store multiple elements in a single variable. These elements are stored as key-value pairs. In fact, you can use an array whenever there’s a need to store a list of elements. More often than not, all the items in an array have similar data types.

For example, let’s say you want to store fruit names. Without an array, you would end up creating multiple variables to store the different fruit names. On the other hand, if you use an array to store fruit names, it might look like this:

1
<?php 
2
$array_fruits = array('Apple', 'Orange', 'Watermelon', 'Mango'); 
3
?> 

As you can see, we’ve used the $array_fruits variable to store the different fruit names. One great thing about this approach is that you can add more elements to the $array_fruits array variable later on.

There are plenty of ways to manipulate array values in PHP—we’ll explore these in the later part of this article.

How to Initialize an Array

In this section, we’ll explore how to initialize an array variable in PHP and add values in that variable.

When it comes to array initialization, there are a few different ways. In most cases, it’s the array() language construct which is used to initialize an array.

1
<?php 
2
$array = array(); 
3
?> 

In the above snippet, the $array variable is initialized with a blank array.

As of PHP 5.4, you can also use the following syntax to initialize an array.

1
<?php 
2
$array = []; 
3
?> 

Now, let’s see how to add elements to an array in this PHP array data structure:

1
<?php 
2
$array = []; 
3
$array[] = 'One'; 
4
$array[] = 'Two'; 
5
$array[] = 'Three'; 
6
echo '<pre>'; 
7
print_r($array); 
8
?> 

The above snippet should produce the following output:

1
Array 
2
( 
3
 [0] => One 
4
 [1] => Two 
5
 [2] => Three 
6
) 

The important thing to note here is that array indices in PHP start with 0. Whenever you add a new element to an array without specifying an index, the array assigns an index automatically.

Of course, you can also create an array already initialized with values. This is the most concise way to declare an array with PHP if you already know what values it will have.

1
<?php 
2
$array = ['One', 'Two', 'Three']; 
3
?> 

How to Access Array Elements

In the previous section, we discussed how to initialize an array variable. In this section, we’ll explore a few different ways to access array elements.

The first obvious way to access array elements is to fetch them by the array key or index.

1
<?php 
2
$array = ['One', 'Two', 'Three']; 
3
 
4
// get the first element of the $array array  
5
echo $array[0]; 
6
echo "<br>"; 
7
 
8
// get the second element of the $array array  
9
echo $array[1]; 
10
echo "<br>"; 
11
 
12
// get the third element of the $array array  
13
echo $array[2]; 
14
echo "<br>"; 
15
?> 

The above snippet should produce the following output:

1
One 
2
Two 
3
Three 

A cleaner way to write the code above is to use a foreach loop to iterate through the array elements.  

1
<?php 
2
$array = ['One', 'Two', 'Three']; 
3
 
4
foreach ($array as $element) { 
5
 echo $element; 
6
 echo '<br>'; 
7
} 
8
?> 

The above snippet should produce the same output, and it takes much less code.

Similarly, you can also use the for loop to go through the array elements.

1
<?php 
2
$array = ['One', 'Two', 'Three']; 
3
$array_length = count($array); 
4
 
5
for ($i = 0; $i < $array_length; ++$i) { 
6
 echo $array[$i]; 
7
 echo '<br>'; 
8
} 
9
?> 

Here, we're using the for loop to go through each index in the array and then echoing the value stored in that index. In this snippet, we’ve introduced one of the most important functions you’ll end up using while working with arrays: count. It’s used to count how many elements are in an array.

Types of Array in PHP

In this section, we’ll discuss the different types of array you can use in PHP.

Numerically Indexed Arrays

An array with the numeric index falls in the category of an indexed array. In fact, the examples we’ve discussed so far in this article are indexed arrays.

The numeric index is assigned automatically when you don’t specify it explicitly.

1
<?php 
2
$array = ['One', 'Two', 'Three']; 
3
?> 

In the above example, we don't specify an index for each item explicitly, so it'll be initialized with the numeric index automatically.

Of course, you can also create an indexed array by using the numeric index, as shown in the following snippet PHP structure:

1
<?php 
2
$array = []; 
3
$array[0] = 'One'; 
4
$array[1] = 'Two'; 
5
$array[2] = 'Three'; 
6
?> 

It is also possible to have arrays with numeric keys which are not sequential or start from zero, like the following example:

1
<?php 
2
 
3
$array = []; 
4
$array[3] = 'One'; 
5
$array[11] = 'Two'; 
6
$array[] = 'Three'; 
7
$array[-18] = 'Four'; 
8
$array[] = 'Five'; 
9
 
10
print_r($array); 
11
/* 
12
Array 
13
( 
14
 [3] => One 
15
 [11] => Two 
16
 [12] => Three 
17
 [-18] => Four 
18
 [13] => Five 
19
) 
20
*/ 
21
?> 

Don't rely on an unknown array in PHP to have sequential numeric keys unless you explicitly set its keys to be that way.

Associative Arrays

An associative array is similar to an indexed array, but you can use string values for array keys.

Let’s see how to define an associative array.

1
<?php 
2
$employee = [ 
3
 'name' => 'John', 
4
 'email' => 'john@example.com', 
5
 'phone' => '1234567890', 
6
]; 

Alternatively, you can use the following syntax as well.

1
<?php 
2
$employee = []; 
3
$employee['name'] = 'John'; 
4
$employee['email'] = 'john@example.com'; 
5
$employee['phone'] = '1234567890'; 
6
?> 

To access values of an associative array, you can use either the index or the foreach loop.

1
<?php 
2
$employee = [ 
3
 'name' => 'John', 
4
 'email' => 'john@example.com', 
5
 'phone' => '1234567890', 
6
]; 
7
 
8
// get the value of employee name  
9
echo $employee['name']; 
10
 
11
// get all values  
12
foreach ($employee as $key => $value) { 
13
 echo $key . ':' . $value; 
14
 echo '<br>'; 
15
} 
16
?> 

As you can see, here we got the name by querying it directly, and then we used the foreach loop to get all the key-value pairs in the array.

Multidimensional Arrays

In the examples we’ve discussed so far, we’ve used scalar values as array elements. In fact, you can even store arrays as elements within other arrays—this is a multidimensional array.

Let’s look at this PHP array example:

1
<?php 
2
$employee = [ 
3
 'name' => 'John', 
4
 'email' => 'john@example.com', 
5
 'phone' => '1234567890', 
6
 'hobbies' => ['Football', 'Tennis'], 
7
 'profiles' => ['facebook' => 'johnfb', 'twitter' => 'johntw'] 
8
]; 
9
?> 

As you can see, the hobbies key in the $employee array holds an array of hobbies. In the same way, the profiles key holds an associative array of the different profiles.

Let’s see how to access values of a multidimensional array.

1
<?php 
2
$employee = [ 
3
 'name' => 'John', 
4
 'email' => 'john@example.com', 
5
 'phone' => '1234567890', 
6
 'hobbies' => ['Football', 'Tennis'], 
7
 'profiles' => ['facebook' => 'johnfb', 'twitter' => 'johntw'] 
8
]; 
9
 
10
// access hobbies  
11
echo $employee['hobbies'][0]; 
12
// Football  
13
 
14
echo $employee['hobbies'][1]; 
15
// Tennis  
16
 
17
// access profiles  
18
echo $employee['profiles']['facebook']; 
19
// johnfb  
20
 
21
echo $employee['profiles']['twitter']; 
22
// johntw  
23
?> 

As you can see, the elements of a multidimensional array can be accessed with the index or key of that element in each array part.

Unpacking Array Values with PHP

Starting from version 7.4, PHP has added the ability to expand arrays in place using the spread (...) operator. 

1
<?php 
2
 
3
$plant_eaters = ["Horse", "Goat", "Rabbit"]; 
4
$meat_eaters = ["Lion", "Tiger", "Crocodile"]; 
5
 
6
$animals = ["Dog", ...$plant_eaters, ...$meat_eaters, "Cat"]; 
7
print_r($animals); 
8
/*  
9
Array  
10
(  
11
 [0] => Dog  
12
 [1] => Horse  
13
 [2] => Goat  
14
 [3] => Rabbit  
15
 [4] => Lion  
16
 [5] => Tiger  
17
 [6] => Crocodile  
18
 [7] => Cat  
19
)  
20
*/ 
21
 
22
?> 

Initially, we could only unpack array values in PHP with numeric keys. However, PHP 8.1 came with support for unpacking arrays with string keys. Here are some examples:

1
<?php 
2
 
3
$default_colors = ["body" => "red", "heading" => "blue", "sidebar" => "yellow"]; 
4
$user_colors = ["body" => "white", "paragraph" => "black"]; 
5
 
6
$theme_colors = [...$default_colors, ...$user_colors]; 
7
 
8
print_r($theme_colors); 
9
/*  
10
Array  
11
(  
12
 [body] => white  
13
 [heading] => blue  
14
 [sidebar] => yellow  
15
 [paragraph] => black  
16
)  
17
*/ 
18
 
19
?> 

You should note that array unpacking in this manner results in overwriting existing values stored in string-based keys, while numeric keys simply get renumbered. Unpacking $user_colors before $default_colors in the above example would have set the value of the body key to "red" in the $theme_colors array.

Some Useful PHP Array Functions

In this section, we'll go through a handful of useful array functions that are used frequently for array operations.

The count() Function

The count() function is used to count the number of elements in an array. This is often useful if you want to iterate an array with a for loop.

1
<?php 
2
$array = ['One', 'Two', 'Three']; 
3
 
4
echo count($array); 
5
// Output: 3  
6
?> 

However, you should be careful when looping over an array with a for loop. This is because there is no guarantee that the numeric keys in an array will always be sequential, start from zero, or be in simple ascending order.

The is_array() Function

This is one of the most useful functions for dealing with arrays. It's used to check if a variable is an array or some other data type.

1
<?php 
2
$array = ['One', 'Two', 'Three']; 
3
 
4
// check if the variable is an array  
5
if (is_array($array)) 
6
{ 
7
 // perform some array operation  
8
} 
9
?> 

You should always use this function before you perform any array operation if you're uncertain of the data type.

The in_array() Function

If you want to check if an element exists in the array, it's the in_array() function which comes to the rescue. 

1
<?php 
2
$array = ['One', 'Two', 'Three']; 
3
 
4
// check if a variable is an array  
5
if (in_array('One', $array)) 
6
{ 
7
 echo 'Yes'; 
8
} 
9
else 
10
{ 
11
 echo 'No'; 
12
} 
13
?> 

The first argument of the in_array() function is an element which you want to check, and the second argument is the array itself.

The explode() Function

The explode() function splits a string into multiple parts and returns it as an array. For example, let's say you have a comma-separated string and you want to split it at the commas. 

1
<?php 
2
$string = "One,Two,Three"; 
3
 
4
// explode a string by comma  
5
$array = explode(",", $string); 
6
 
7
// output should be an array  
8
echo '<pre>'; 
9
print_r($array); 
10
 
11
// output  
12
/*Array  
13
(  
14
 [0] => One  
15
 [1] => Two  
16
 [2] => Three  
17
)*/ 
18
?> 

The first argument of the explode() function is a delimiter string (the string you're splitting on), and the second argument is the string itself.

The implode() Function

This is the opposite of the explode() function—given an array and a glue string, the implode() function can generate a string by joining all the elements of an array with a glue string between them.

1
<?php 
2
$array = ['One', 'Two', 'Three']; 
3
 
4
$string = implode(",", $array); 
5
 
6
// output should be a string  
7
echo $string; 
8
 
9
// output: One,Two,Three  
10
?> 

The first argument of the implode() function is a glue string, and the second argument is the array to implode.

The array_push() Function

The array_push() function is used to add new elements to the end of an array.

1
<?php 
2
$array = ['One', 'Two', 'Three']; 
3
array_push($array, 'Four'); 
4
 
5
echo '<pre>'; 
6
print_r($array); 
7
 
8
// output  
9
/*Array  
10
(  
11
 [0] => One  
12
 [1] => Two  
13
 [2] => Three  
14
 [3] => Four  
15
)*/ 
16
?> 

The first argument is an array, and the subsequent arguments are elements that will be added to the end of an array.

The array_pop() Function

The array_pop() function removes an element from the end of an array.

1
<?php 
2
$array = ['One', 'Two', 'Three']; 
3
$element = array_pop($array); 
4
 
5
echo '<pre>'; 
6
print_r($array); 
7
 
8
// output  
9
/*Array  
10
(  
11
 [0] => One  
12
 [1] => Two  
13
)*/ 
14
?> 

The array_pop() function returns the element which is removed from an array, so you can pull it into the variable. Along with array_push(), this function is useful for implementing data structures like stacks.

The array_slice() Function

The array_slice() function is useful when you want to extract some portion of a given array. It accepts four parameters: the array, the index from which to slice, the number of elements to slice, and whether to preserve the numerical key. The function will always preserve string keys, irrespective of the fourth parameter.

1
<?php 
2
 
3
$people = ["Adam", "Amanda", "Andrew", "Laura", "Monty", "Sally", "Sajal", "Steven"]; 
4
 
5
$members = array_slice($people, 2, 4); 
6
print_r($members); 
7
/*  
8
Array  
9
(  
10
 [0] => Andrew  
11
 [1] => Laura  
12
 [2] => Monty  
13
 [3] => Sally  
14
)  
15
*/ 
16
?> 

The offset value can also be negative. In that case, the slicing position will be determined from the end of the array.

The array_splice() Function

Th array_splice() function is useful when you want to get rid of a portion of an array and/or replace it with something else. It also accepts four parameters: the array, the offset index from which to begin the removal, the length to remove, and an optional replacement for the removed values.

1
<?php 
2
 
3
$all_items = ["Charger", "Keyboard", "Smartphone", "Baseball", "Bat", "Mouse"]; 
4
$replacements = ["Pen", "Headphones"]; 
5
 
6
array_splice($all_items, 3, 2, $replacements); 
7
print_r($all_items); 
8
/*  
9
Array  
10
(  
11
 [0] => Charger  
12
 [1] => Keyboard  
13
 [2] => Smartphone  
14
 [3] => Pen  
15
 [4] => Headphones  
16
 [5] => Mouse  
17
)  
18
*/ 
19
?> 

That's It—Now You Know What an Array in PHP is!

That's all you need to know to get you started coding with arrays in PHP. You saw how to create arrays and how to retrieve elements from them. You learned the different types of arrays in PHP, and you got a look at some of the most useful built-in PHP functions for working with arrays.

Editorial Note: This post has been updated with contributions from Gonzalo Angulo. Gonzalo is a staff writer with Envato Tuts+.