PHP Array - Indexed, Associative and Multidimensional With Examples

An array is a group of similar types of variables. PHP provides function array() to create a PHP array.

PHP Array

There are three types of arrays in PHP.

  1. Indexed arrays – Array with numeric indexes.
  2. Associative arrays – Array with key-value pairs, its similar to Map in java.
  3. Multidimensional arrays – An array of arrays.

PHP Indexed arrays

There are two ways to create indexed arrays.
– first way to use array() function without any index, index are assigned automatically starting from 0.
– second way to manually assign index and create the array.

PHP count() function is used to get the length of an array. We can use for loop to loop through all the values of an indexed array.

Below code shows both the ways to create an indexed array and loop through them in PHP.

PHP Associative Arrays

Associative arrays uses named keys for values and we can create them in similar way like indexed arrays. foreach is used to loop through an associative array.

output of above PHP script is:

Multidimensional Array in PHP

A multidimensional array is an array of arrays. We can create two-dimensional, three-dimensional and n-dimensional arrays using array function.

Each array within the multidimensional array can be either indexed array or associative array. We can use for loop for looping through indexed array and foreach for looping through associative array.

In below example, I am showing two-dimensional indexed arrays and mixture of indexed and associative array in multidimensional array.

We can use print_r() or var_dump() function to print the human readable form of the array.

The output of above PHP script is:

In next posts, we will look into some common array functions.

Earlier articles for PHP tutorial:

  1. PHP Tutorial for Beginners – PHP Syntax, Comments, Variables and Scope
  2. PHP Operators – Arithmetic, Comparison, Logical, Bitwise Operators
  3. PHP if-else, Switch Case and Shorthand Ternary operator

By admin

Leave a Reply

%d bloggers like this: