A PHP array is one of the most basic forms of PHP variables — and one of the most important. While most PHP variables will only contain a single value, an array contains an entire list of values. 

In this article, we’ll take a look at how to create, modify, and access an array. We’ll also look at different types of arrays (including multidimensional arrays) and how we can use them.

Person in front of computer, coding

What is a PHP array?

An array is a feature of many languages, denoting a variable that contains an array of elements. Think of an array like a grocery list.

What do you need to buy from the store?

In an array, this would be:

	$groceries[0] = "Milk";
	$groceries[1] = "Eggs";
	$groceries[2] = "Apples";

Alternatively, you could create an array like this:

	$groceries = array('Milk','Eggs','Apples');

Why is an array great? Because it contains the entirety of your list. If you wanted to print out your entire list, you could. If you wanted to add things to the list, you could.

Arrays are a way of not just storing data, but also organizing data. Arrays can create a rudimentary “database” and are critical to data management. Learning how to manipulate arrays is one of the first tasks you’ll face when becoming a PHP programmer.

PHP for Beginners – Become a PHP Master – CMS Project

Last Updated October 2022

Bestseller
  • 336 lectures
  • All Levels
4.4 (22,954)

PHP for Beginners: learn everything you need to become a professional PHP developer with practical exercises & projects. | By Edwin Diaz, Coding Faculty Solutions

Explore Course

How PHP treats arrays: strict typing and indexing

The PHP function for arrays is a little different from others. In PHP, arrays aren’t strictly typed. That means that you could have an array of entirely different items:

	$array[0] = "Cats";
	$array[1] = 3;
	$array[2] = "3.4";

This isn’t proper in most other programming languages. Most other languages require that an array be strictly typed (only a single type of variable, such as a string or an int).

Another unique item is that you don’t need to use an array push to add to an array. In many languages, an array needs a special “sequence” to push items onto the array or pop items from the array.

In PHP, you can add an item to an array simply by declaring it with an index:

	$array[4] = "New array item.";

This flexibility in PHP makes array functions a lot easier to use. There’s no array type, making it easier to create an array and manipulate the elements in the array. An indexed array doesn’t even need all the indexes identified; you can skip them as you add indexes to an existing array.

However, this flexibility also means that you have more leeway to make mistakes. If you’re prone to errors like putting a string value in where an int value should be, you may want to turn on strict typing.

Declaring an array in php

To use an array, you first need to declare it. PHP is a little special in that you can declare an array by assigning a value to it.

Consequently, you can declare an array as follows:

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

Or you can declare it as such:

	$array[0] = 1;
	$array[1] = 2;
	$array[2] = 3;
	$array[3] = 4;

In most other programming languages, you would need to declare the value first:

	let array $array;
	$array = array(1,2,3,4);

PHP doesn’t require, by default, that you declare variables before you start working with them. This is both good and bad. It’s good because it’s a step you don’t need to take. It’s bad because you could easily assign attributes to an incorrect array. 

For instance, we could start adding values to an array like this:

	$array[0] = 1;
	$array[1] = 2;
	$array[2] = 3;
	$array[3] = 4;

If we didn’t catch that typo, we would be perplexed as to why our array didn’t include the right number! We would have declared two arrays completely by accident, because it’s so easy to declare an array by mistake.

And because, again, PHP doesn’t care about data type, we could accidentally type in:

	$array[3] = '4';

That’s not a number! It’s a string. Some PHP functions may treat it as a number, but under strictly typed functions, it gets treated as a char. That’s why it’s so important to pay attention to your assignments — and why a lack of strict typing can be a little dangerous.

Fence post errors with arrays

Fence post errors are very common with arrays. What is a fence post error? It’s also known as an “off by one” error.

Arrays always start at [0], not [1]. So, an array with 4 elements is numbered 0 through 3.

Let’s take the following code example:

$fruits = array("Apples","Bananas","Pears");

for($i = 1; $i <= 3; $i++) {
    echo $fruits[$i];
    echo "<br>";
}

This results in the following:

	Bananas
	Pears
Fence post errors with arrays, php

What happened?

It’s an “off by one” or “fencepost” error. We started at 1 when we needed to start at 0, and we ended at 3 when we needed to end at 2.

Fence post errors with arrays resolved, php

This code is much better. Now we start at 0 — which we should always do when iterating through an array — and we swapped the hard-coded number “3” with sizeof($fruits). The sizeof function returns the size of an array every time. This makes it perfect for iterating through an existing array.

Fence post errors are extremely common in programming because it’s not intuitive to start with 0 rather than 1. Another form of fencepost error is the following:

	$i < sizeof($fruits)

Using < rather than <= or > rather than => is another type of “off by one” error. If you’re counting from 1 to 12, using < will count from 1 to 11 rather than 1 to 12. Once you learn to identify fence post errors (you either start or end a list in an unexpected place), they become easy to fix.

Adding to a PHP array with ARRAY_PUSH

You can modify a PHP array, which is part of what makes it so useful. At any time, you can make your list a little longer. 

Let’s say we have our grocery list again:

	$groceries = array("Milk","Eggs","Apples");

But now we need to add turkey. We can use the ARRAY_PUSH method:

	array_push($groceries, "Turkey");

The ARRAY_PUSH syntax is:

	array_push($array, $new_item);

The parameters given are:

Note that the ARRAY_PUSH method does not require you to assign the value; it automatically changes the value of the given array. Doing something like this is incorrect:

	$array = array_push($array, $new_item);

It’s important to note this because in PHP, a lot of functions such as CONCAT do return the new string. But in the case of most array functions, the array function itself modifies the array rather than returning an array.

ARRAY_PUSH is also unique in that it can take a large number of parameters. If you wanted to add multiple items, you could use the following:

	array_push($groceries, "Turkey", "Ham");

Here’s another method we could use:

	$groceries[sizeof($groceries)] = "Turkey";
	$groceries[sizeof($groceries)] = "Ham";

What did we just do? We took the size of groceries (3) and we added a new array variable there. We didn’t need to add +1 because the size is always going to be the next variable index (because of the before-mentioned fence post; the array starts at 0).

Since the size of the array went up with “Turkey,” the size is still correct when we move on to “Ham.”

We could also have done this:

$groceries[3] = "Turkey";
$groceries[4] = "Ham";

But regardless, the ARRAY_PUSH method is generally best. It’s very similar to the PUSH methods used in other languages, such as C, and it’s going to cause fewer potential issues.

But what if you needed to add an item in the middle of the array? Then you would want to use the ARRAY_SPLICE function, which we are going to discuss in the next section.

Adding and removing from a PHP array with ARRAY_SPLICE

In a lot of data structures, removing an item from an array is called “popping.” You “pop” an item off an array. So, you might have an array of:

	0: Cats
	1: Dogs
	2: Birds

And you’d “pop” cats, to make it:

	0: Dogs
	1: Birds

But that’s not how it works in PHP. 

In PHP, you can unset a given variable, but it’s not going to do exactly what you want if you’re trying to redo the entire array:

	$pets = array('Cats','Dogs','Birds');
	unset($pets[1]);

This will remove dogs from the list (and who would want to do that). But cats will still be in position 0 and birds will still be in position 2. You’ll just have a blank hole in position 1.

So, to unset a variable, it’s actually better to splice it. The array_splice PHP function both removes and reindexes from the array:

$pets = array('Cats','Dogs','Birds');
array_splice($pets,1,1);

This will remove “dogs” from the array and will make it an array of the size “2” rather than the size “3”. Splicing is a better practice because it means you’re not going to have empty values within your array.

The splice_array syntax is as follows:

array_splice($array, $start, $length, $new_array);

 The given parameters are:

Similarly, you can splice into the array.

	$fruits = array("Apples","Pears","Bananas");
	$new_fruits = array("Pineapples");
	array_splice($fruits,1,0,$new_fruits);

In the above, you need two arrays. The new_fruits array is spliced into the fruits array at position 1. So, while it’s called an ARRAY_SPLICE, it’s really an array merge function.

Finding an item in an array with PHP IN_ARRAY

What if you want to know whether an item is in an array? For that, you use the PHP IN_ARRAY function. This usual function tells you whether something is included.

	$craftsupplies = array("Pens","Paper","Glue","Stickers");
	
	if(in_array("Pens", $craftsupplies)) {
		echo "We brought pens!";
	}
PHP IN_ARRAY function example

We can also use this to check for the absence of an item:

! before php IN_ARRAY function

This code works because the addition of ! before the IN_ARRAY function indicates that it’s not true.

The IN_ARRAY function syntax is as follows:

in_array($needle,$haystack);

The parameters given are:

This is one of the simplest array search functions out there, in terms of data structures, but it’s also very powerful.

Creating an array without integer keys

PHP has another unique function among keyed arrays, because a lot of languages only let you create an array with numbers. But you don’t need an integer key to use an array. You can actually use any key you want.

    $supplies["Paper"] = 1;
    $supplies["Pencils"] = 1;
    
    if($supplies["Paper"]) {
    	echo "Yes, we have paper<br>";
    }
    
    $supplies["Paper"] = 0;
    
    if(!$supplies["Paper"]) {    
    	echo "We are out of paper";
    }

In the above example, rather than using 0 and 1, we’re using the keys of “Paper” and “Pencils” and storing the quantity of each within the array. We then call the array using the string “Paper” and “Pencils” rather than using a number 0 or 1.

php array without integer keys example

You can use any regular array operation this way. However, you wouldn’t be able to iterate through this array using numbers. Instead, you could use the FOREACH command.

Iterating through an Array with FOR Loops and FOREACH

There are a lot of ways to iterate through an array (list every item). The two most popular are “FOR” and “FOREACH.”

A FOR loop can work for any numerical array. FOR loops are commonly featured in many languages, such as Python, and always operate in much the same way:

   for($i = 0; $i<sizeof($colors); $i++) {
    		echo $colors[$i];
       	echo "<br>";
    }
Php array with FOR Loops

FOR loops appear complicated, but they really aren’t. They’re one of the most useful tricks you can use.

The syntax is as follows:

	for($starting_value,$condition, $ending_increment) {
		$code_block;
	}

The parameters include:

In simple terms, the “FOR” loop starts a variable at 0. While that variable is less than the size of the array, the code block runs. After the code block runs, the variable gets incremented by 1.

But you can see that this won’t work for an array map that doesn’t include numbers. For that, we need to use FOREACH.

   $colors["One"] = "Blue";
    $colors["Two"] = "Green";
    $colors["Three"] = "Yellow";
    $colors["Four"] = "Orange";
    $colors["Five"] = "Red";
    
    foreach($colors as $color) {
    	echo $color;
        echo "<br>";
    }
php foreach

FOREACH iterates through an array. As it does so, it reassigns the current value to a temporary variable that can then work in the code block.

	foreach($original_array as $temporary_variable) {
		$code_block;
	}

Parameters:

When working with arrays, FOREACH is almost always recommended.

Creating multidimensional arrays

A multidimensional array is an array of arrays. Each array item can actually be an array unto itself. For instance, you could do this:

	$names[0] = array("John","Doe");
	$names[1] = array("Jane","Smith");

$names[0] now returns an array that includes “John” and “Doe.” You could iterate through each of these arrays to get the complete name of each person.

To iterate through multidimensional arrays, you would simply need to create nested FOREACH loops. You might also want to create a PHP schema so you are aware of what data is being saved where.

Another example of a multidimensional array might be one to keep a customer profile in:

	$customers[0]["Name"] = "John Doe";
	$customers[0]["Email"] = "[email protected]";
	$customers[0]["Phone"] = "(123) 444-4444";

From there, when you wanted to iterate through your customers, you could do something like this:

	foreach($customers as $current_customer) {
		echo $current_customer["Name"];
		echo "<br>";
		echo $current_customer["Email"];
		echo "<br>";
	}

Multidimensional arrays are frequently used in procedural programming to mimic object-oriented programming. They can also model complex, related data, much like a database would.

In the above example, you’re able to iterate through an entire list of data and connect multiple pieces of data (name, email, and phone). You’re also able to use an easy method of referencing that data (“name” rather than 0).

What’s next?

Now you know everything you need to know about the PHP ARRAY function. PHP arrays are one of the easiest methods of storing lists of data. By using an array, you’ll be able to organize your data better and iterate through it as desired.

The best way to learn more about PHP is to go through a PHP bootcamp or a backend web development (PHP/MySQL) course. This will teach you more about arrays and functions.

Page Last Updated: February 2022

Top courses in PHP

PHP Unit Testing with PHPUnit
Dave Hollingworth
4.6 (1,758)
Bestseller
PHP for Beginners - Become a PHP Master - CMS Project
Edwin Diaz, Coding Faculty Solutions
4.4 (22,954)
Bestseller
PHP with Laravel for beginners - Become a Master in Laravel
Edwin Diaz, Coding Faculty Solutions
4.5 (11,873)
Bestseller
APIs in PHP: from Basic to Advanced
Dave Hollingworth
4.7 (443)
Object Oriented PHP & MVC
Brad Traversy
4.6 (4,519)
PHP for Beginners
Tim Buchalka's Learn Programming Academy, Dave Hollingworth
4.6 (2,764)

More PHP Courses

PHP students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo