PHP array: Indexed, Associative and Multidimensional

What is PHP Array

Array is a collection of data or items of similar data types. PHP uses Dollar($) sign to define any array variable. Use of array is a good practice in PHP coding when you have multiple values to store in one single variable.

Suppose you want to store three values of similar types. You write something like as given below:

But what happen if you have hundreds or thousands of values of similar types. It’s very difficult to create many variables and handle them using PHP coding. In that case, PHP array is a good practice to store multiple values in one single variable.

Types of PHP Array

There are three types of PHP arrays to store multiple values:

  • Indexed Array: An array with numeric key values.
  • Associative Array: An array with string index keys for each values.
  • Multi-dimensional Array: An array used to store one or more arrays and its values.

PHP Indexed Array

The PHP indexed arrays is an array storing each element or items with numeric index values. The array elements are by default start from numeric index zero(0).

There are two ways to store index array values:
Indexed array types I: Automatically assign index
This is the easiest way of creating indexed array. In this array, the index starts from zero(0).

Indexed array types II: Manually assign index
In this, the array values are indexed manually and starts from zero(0).

How to retrieve indexed array

You can use PHP foreach loop to retrieve each element of indexed array. It’s very simple to iterate through each elemennt of indexed array.

To print each element after you retrieve each element, you can use PHP echo statement.
Example: Showing on how to retrive and print each element of indexed array

Output

Steven Smith
Virat
AB de Villiers

PHP Associative Array

The PHP associative array is a PHP array storing each element with an assigned keys of string type. The keys are of string type and defined by the user manually.

There are two ways to store associative array values:

Associative array types I
This is the easiest way of creating associative array with keys assigned to each vsalues.

Associative array types II
This is the other way of creative associative array with values same as above.

PHP Multi-dimensional Array

A multi-dimensional array is PHP array in which each elements or items can also be an array. The variable in multi-dimensional array stores one more arrays.

It’s difficult for web developers to operate multiple values inside multidimensinal array. However, you can use multiple index to access each values in multi-dimensional array.

Below here is an example of multidimensionalarray:-

Output

Sachin score 86 in physics.