Learn to use simple and associative arrays in PHP with examples

PHP array types

In PHP, there are three types of arrays. Each of these types is explained below:

PHP Numeric Arrays

This is a PHP array type with the numeric index where an array stores each element with a numeric index (array key).

The numeric array type can store strings, numbers and objects, however, its index is represented by numbers.

The default array key starts with 0.

A Numeric Array example

Following example shows how to create array elements of a PHP numeric array.

PHP numeric array

Experience this example online

To display this array in PHP program

This is how you can print array elements of a numeric array by using the PHP echo statement.

PHP Associative array

The Associative array is an array type with strings used as the index rather numbers. This array type is just like numeric arrays except the index style.

An associative array has its index as a string so that you can establish a strong association between the keys and values.

This really helps in establishing a strong link between array keys and values, as explained in employee/salary example below.

If you require storing the salaries of your employees in an array, a numeric-indexed array can’t be the best choice and may always be confusing. For example, this is how a numeric array will be created:

In this case, the PHP associative array plays its role.

In the above example, we can use the associative array to store salaries with employees names as the keys, and the value would be their respective salary.

An example of associative array

The following example creates three array elements by string index.

Experience this example online

Now see the difference, how easy it will be to identify by descriptive index keys.

PHP Multidimensional array

The multidimensional array is an array type that contains one or more arrays. In this array type, the elements are accessed by using multiple indices.

Alternatively, in this array, an element in the main array may also be an array (sub-array) and each element in the sub-array can also be an array and so on.

Or we can say, this array type has rows and columns (the previous two are the one-dimensional array, with one column of elements.)

Example of PHP multidimensional array

Experience this example online


In the above example, see how a multidimensional array is storing and referred.

Was this article helpful?

Related Articles

Leave A Comment?