Login | Contact Us | Site Map | Resources

PHP Arrays

Home > PHP Tutorial > What is a PHP array?

What is a PHP array?

An array is a variable that can store multiple values instead of just one. The values in an array can be referenced either collectively or individually.

You can create as many variables as you need to store your data individually, but what if that data is all related and you want to search through it, or sort it in a particular way? Storing related data in an array will allow you to perform these functions and many more.

Let's say that you have a list of animals that you want to store temporarily. Normally, it would look something like this:

<?php
  $animal1 = "dog";
  $animal2 = "iguana";
  $animal3 = "giraffe";
  $animal4 = "fish";
  $animal5 = "tiger";
?>

Each animal is stored in a separate variable, making it difficult or even impossible to list, sort, search and compare each value. Storing the same values in a single array might not look much different at first, but the possibilities for handling the data become much greater.

<?php
  $animals[0] = "dog";
  $animals[1] = "iguana";
  $animals[2] = "giraffe";
  $animals[3] = "fish";
  $animals[4] = "tiger";
?>

There are three different types of arrays.

Numerical arrays, shown in the example above, use numbers as the "key" that references each value stored in an array. The value of a numerical array begins with 0 instead of 1. This is the default array type.

Associative arrays use a unique ID key, specified by the programmer, to reference each value stored in an array.

Multidimensional arrays are arrays that contain another array, or more than one other array.

Arrays are often described as maps, with each key being mapped to a value. Any way that you want to think of them, arrays can be quite useful once you wrap your head around them. Let's move on and learn more about creating arrays.