PHP Arrays

An array can store many values at once within a single variable.

What is PHP Arrays

Arrays are complex variables that stores multiple or a group of values under a single variable name. Let’s suppose you want to store 10 numbers in your PHP script. Storing the numbers one by one in a variable could look something like this:

It is easy to take variables for that small amount of numbers. But what if you want to store say 50 or 100 or even 1000 numbers? Will you take that much of variables to store the value?I think this is not a good approach to take that much variables to store the data. The solution for this is: “Array”

Have a look at the following example where we are storing the 10 variables again but this time using array. You will not the difference in the code.

Just look at the number of lines in the first and second code. First code is of 22 lines but the second done the same job in just 6 lines. This is how PHP Arrays are used.  Also in the first program, we took 10 variables to store data of 10 variables but secondly, we needs just only one variable.

Types of Arrays in PHP

There are three types of arrays that you can create. These are:

  • Indexed array — An array with a numeric key.
  • Associative array — An array where each key has its own specific value.
  • Multidimensional array — An array containing one or more arrays within itself.

Indexed Arrays

An indexed or numeric array stores each array element with a numeric index. The following examples shows two ways of creating an indexed array, the easiest way is:

The output will looks like:

array

Note:In an indexed or numeric array, the indexes are automatically assigned and start with 0, and the values can be any data type.

Associative Arrays

In an associative array, the keys assigned to values can be arbitrary and user defined strings. In the following example the array uses keys instead of index numbers:

The output will looks like:

Multidimensional Arrays

The multidimensional array is an array in which each element can also be an array and each element in the sub-array can be an array or further contain array within itself and so on. An example of a multidimensional array will look something like this:

In this tutorial you have learnt about PHP Arrays. If you have any question regarding PHP Arrays, you can raise it at our Forum Section.

Loading