PHP - Two types of Arrays

Introduction

PHP support two types of arrays:

TypeDescription
Indexed arrays each element is referenced by a numeric index, usually starting from zero.
Associative arraysa hash or map.

Creating Arrays

The simplest way to create a new array variable is to use PHP's built-in array() construct.

This takes a list of values and creates an array containing those values, which you can then assign to a variable:

$authors = array("A","B","C","D");

Here, an array of four elements is created, with each element containing a string value.

The array is then assigned to the variable $authors.

You can access any of the array elements via the single variable name, $authors, as you see in a moment.

This array is an indexed array, which means that each of the array elements is accessed via its own numeric index, starting at zero.

In this case, the"A" element has an index of 0, "B" has an index of 1, "C" has an index of 2, and "D" has an index of 3.

Associative array

To create an associative array, where each element is identified by a string index rather than a number, use the => operator, as follows:

$myBook = array("title"=> "Java",
                "author"=> "John A",
                "pubYear"=>  2018);

This creates an array with three elements: "Java", which has an index of "title"; "John A", which has an index of "author"; and 2018, which has an index of "pubYear".

Related Topic