How To Use Arrays In PHP

Eric Tam
2 min readOct 13, 2021

--

Colin Viebrock, CC BY-SA 4.0, via Wikimedia Commons

In this tutorial, we will begin learning about arrays.

What Are Arrays?

An array is a special variable that can store multiple related values; this is in contrast to regular variables that can store only one value at a time.

Why Use Arrays?

If you have a number of fruits, you can store them separate like this

<?php
$fruit1 = "orange";
$fruit2 = "apple";
$fruit3 = "mango";
?>

However, one problem with using separate variables is that you lack a convenient way to loop through them.

And this is where an array is useful: it allows you to easily loop through a number of related variables using a foreach loop.

An array can hold many related values in the same variable and access each value using an index(also known as a key).

Creating an Array

To create arrays in PHP, you use the following syntax:

$arr = [];

Alternatively, you can also write:

$any = array();

The above codes do the same thing; they create an empty array.

Arrays all have some things called keys and values.

The key is which unit we are interested in; different values are stored with different keys.

Values are what each item of the array equals.

Setting specific key values is optional: by default, the keys for an array are 0,1,2,3,4,5,6 in ascending order.

Hence, the key for the first item in the array is 0 and the second item’s key is 1.

And this what you would get for this array below.

<?php
$arr =["a", "b", "c", "d"];
echo $arr[0]; //$arr[0] equals a echo $arr[1]; //$arr[1] equals becho $arr[2]; //$arr[2] equals c

echo $arr[3]; //$arr[3] equals d
?>

Result

However, you are free to assign whatever key values you wish in your array.

Types Of Arrays

In PHP, there are three different types of arrays:

Indexed arrays: these are arrays with numbers as keys.

Associative array: this is a fancy way of saying “arrays where the keys are not numbers”.

Multidimensional array: these are “arrays of arrays”: the value of the keys are themselves arrays.

--

--

Eric Tam

A self taught software developer currently working with HTML, CSS, Javascript and PHP.