PHP Arrays Tutorial

In this tutorial lesson we will learn about Arrays, and how they allow us to store multiple data elements in a single container.

What is an array?

An array in PHP is a data type that allows storage of many data elements in a single container, as key/value pairs. We can think of it as a container that can hold many variables.

As an example, let’s consider the word “Hello”. The word consists of 5 separate letters, combined into something that provides meaning.

Now consider a table with a single row and 5 columns, where each cell contains one letter.

Hello

To create the word “Hello” from this table, we would need to output the letters of the table in sequence.

A string is actually an array of single characters. In a language like C, there is no string data type and we would instead need to create a word or a sentence as an array.

PHP stores array elements as key/value pairs. Every letter in our array has a corresponding number, or word, that we can use to get access to the element value.

01234
Hello

By default, the lowest number corresponds to the first element in the array.

Arrays with numerical indexes will always start at 0, not at 1.

It’s beneficial to use an array, instead of many variables, when working with larger amounts of data that we will access together.

Array elements get stored in memory together, in sequence. This means that lookup processing is faster, allowing the application to be more performant.

How to create an array

In PHP, there are three types of arrays:

  • Indexed arrays are arrays with a numeric index.
  • Associative arrays are arrays with named keys as key/value pairs.
  • Multi-dimensional arrays are arrays that contain one or more arrays inside them.

We create, or define, arrays in one of two ways:

  • By using the array() function.
  • By using the shorthand square brackets [ ] in PHP v5.4+.

How to define an indexed array with square brackets

The easiest method to define an array is to assign multiple, comma separated values between square brackets to a variable.

This method of definition is also the most common, which is why we introduce it first.

Syntax:
 $arrayName = [value1, value2, value3, ...];
Example: 5.4+ array definition with square brackets
<?php

$arr = ["Hello", 3.14, -59870, "Arrays are cool"];

?>

The syntax in the example above is only available in PHP 5.4 and up.

Another thing to note is that, unlike many other languages, like C, we can store different data types in the same array.

How to define an indexed array with the array() function

The original method to create an array is to use the array() function.

We specify the word array , immediately followed by parentheses. Inside the open and close parentheses, we specify a comma-separated list of values.

Syntax:
 $arrayName = array(value1, value2, value3, ...);
Example: array definition with array() function
<?php

$arr = array("Hello", 3.14, -59870, "Arrays are cool");

?>

The definition of the array is almost identical to the shorthand, except for the function syntax.

How to access elements in an array

PHP provides us with two methods to access the values of an array:

  • The Indexer, that can specify single specific elements.
  • Loops, that can iterate over all the elements inside an array.

How to access array elements with the indexer

The indexer allows us to access a single value at a specific numerical index in the array. The indexer is a pair of open and close square brackets [ ] , with the index number between them.

Syntax:
 $arrayName[index];
Example: access array with the indexer
<?php

$arr = ["Hello", 3.14, -59870, "Arrays are cool"];

echo $arr[0];

?>

The example above will print the value at index 0 (Hello), to the page.

If we try to use an index for a value that doesn’t exist, the interpreter would raise an error.

How to access array elements with a foreach loop

If you are a beginner, loops and iteration control may not make much sense at this point. We cover looping again in the Iteration Control: Foreach tutorial lesson, so it’s okay if you don’t understand them right now.

Because an array is a collection of many values, it makes sense to use a control structure that can access all those values in one execution. One of these structures is called a foreach loop.

In a foreach loop, the interpreter will go through the array, one value at a time, and store it in a temporary variable.

We then access each array element, with that temporary variable, inside the loop’s execution block.

Syntax:
foreach($arrayName as $tempVar) {
   // do something with $tempVar
}
Example:
<?php

$shopping = ["Milk", "Bread", "Eggs"];

foreach($shopping as $item) {
    echo $item . "<br>";
}

?>

The loop in the example above reads as follows:

for each $shopping element as $item, echo the $item

Associative arrays with custom key/value pairs

PHP provides us with the option to define our own custom indexes, known as keys. Keys are linked to values in the same way that the numerical index is linked.

How to define custom keys

We link a key to a value with an equals = and greater than > symbol.

Each key must be unique to other keys, but can be the same as other values.

Syntax:
 $arrayName = [key1 => value1, key2 => value2, ...];
Example: custom key-value pairs
<?php

$arr = [
    "Msg" => "Hello",
    "Pi" => 3.14,
    1 => -59870,
    2 => "Arrays are cool"
];

?>

In the example above, the first two keys are string types, and the second two are int types.

PHP allows keys in associative arrays to be of different types, but it’s considered bad practice because the code is inconsistent and hard to read.

How to access associative array elements with the indexer

We can access elements in an associative array by using the indexer. Instead of the typical numerical index, we specify the key linked to the value that we want to access.

Syntax:
 $arrayName[key];
Example: access associative array elements with the indexer
<?php

$arr = [
    "Msg" => "Hello",
    "Pi" => 3.14,
    1 => -59870,
    2 => "Arrays are cool"
];

echo $arr["Msg"] . "<br>";
echo $arr["Pi"] . "<br>";
echo $arr[1] . "<br>";
echo $arr[2] . "<br>";

?>

In the example above, we access the elements in the array through their keys, instead of the default numerical index.

How to access associative array elements with a loop

When we access associative array values, we assign a temporary variable to both the key and the value.

Other than that specific syntax change, the foreach loop is executed in the same way as before.

Syntax:
foreach ($arrayName as $key => $value) {
    execution statement
}
Example: access associative array elements in a loop
<?php

// Associative Array
$num = array(
    "One" => 1,
    "Two" => 2,
    "Ten" => 10
);

// Foreach access key/value
foreach ($num as $key => $value) {
    echo "Key: " . $key . " / Value: " . $value;
    echo "<br>";
}

?>

We don’t necessarily need to include the key, we can access an associative array as before.

Example: access without key
<?php

// Key/Value Array
$num = array(
    "One" => 1,
    "Two" => 2,
    "Ten" => 10
);

// Foreach access key/value
foreach ($num as $value) {
    echo "Value: " . $value;
    echo "<br>";
}

?>

The example above doesn’t raise any errors, even though it’s not using keys.

How to change array values

Arrays are mutable, which means that array values can be changed at runtime.

Changing values in an array is similar to changing values in variables, except that we have to specify the key, or index, of the value in the array that we want to change.

We assign a new value to the specific array element with the assignment operator.

Syntax:
 $arrayName[key/index] = new_value;
Example: change array element's value
<?php

// Define array
$arr = ["Msg" => "Hello"];
echo $arr["Msg"] . "<br>";

// Change value
$arr["Msg"] = "Greetings";
echo $arr["Msg"];

?>

In the example above, we change the word Hello to Greetings with assignment to the Msg array key.

How to remove elements from an array

We can remove individual array elements with the unset() function. To remove an element we specify the array name and key/index in between the unset() function’s parentheses.

Syntax:
 unset($arrayName[key/index]);
Example: remove single elements with unset()
<?php

$arr = [
    "Msg" => "Hello",
    "Pi" => 3.14,
    1 => -59870,
    2 => "Arrays are cool"
];

echo $arr["Msg"] . "<br>";

// Delete element
unset($arr["Msg"]);

echo $arr["Msg"] . "<br>";

?>

In the example above we print the Msg element to the page, then delete it and try to print it again.

The interpreter will execute the first echo statement, but when it comes to the second echo, it will raise an error.

Output: undefined index error
Hello

Notice: Undefined index: Msg on line 15

How to delete an array

Deleting an array completely uses the same unset() function, except we don’t specify an element key/index.

Syntax:
 unset($arrayName);
Example: delete array
<?php

$arr = [
    "Msg" => "Hello",
    "Pi" => 3.14,
    1 => -59870,
    2 => "Arrays are cool"
];

echo $arr["Msg"] . "<br>";

// Delete array etirely
unset($arr);

echo $arr["Msg"] . "<br>";

?>

This time, the interpreter will raise a different error when we try to print an array element to the page, saying that the $arr variable is undefined.

Output: undefined variable error
Hello

Notice: Undefined variable: arr on line 15

It is important to remember that the unset() function can delete a single element or the whole array, and we must be careful when working with it.

Summary: Points to remember

  • An array is a container for multiple data elements.
  • Arrays with numerical indexes will always start at 0.
  • Arrays can be defined with the indexer or the array() function.
  • Array elements can be accessed with the indexer or with loops such as the foreach or while loop.
  • Associative arrays have custom key/value pairs instead of numerical_index/value pairs.
  • Associative arrays can be accessed with the indexer or with loops such as the foreach or while loop.
  • We change the value of an array element by referencing the index/key of the element, and assigning a new value with the = operator.
  • We remove individual array elements with the unset() function, but we must specify a key/index.
  • We delete an array entirely with the unset() function. In this case we do not specify the key/index.