This post will discuss how to create and initialize an array in PHP.

1. Using array() construct

A simple approach to initialize an array in PHP is using the array() construct. It takes "key => values" pairs, where key may be of type string or integer.

The following example creates an associative array using the array() construct.

Download  Run Code

 
When two identical indexes are defined, the last overwrite the first, as demonstrated below:

Download  Run Code

 
If the key is omitted, PHP will generate integer keys beginning from 0, as shown below:

Download  Run Code

 
In the following example, since index 0 is defined twice, the latter value of ‘B’ is assigned to it.

Download  Run Code

 
You can also create a 1-based array in PHP, as shown below:

Download  Run Code

 
The following example demonstrates how to create a two-dimensional array:

Download  Run Code

2. Using [] syntax

PHP 5.4+ offers the short array syntax [], eliminating the need for array() construct. It works similarly and avoids the overhead of calling a function.

Download  Run Code

Download  Run Code

3. Using $arr[] = $val syntax

If you’re unsure of the contents of the array, you can create an empty array and push values onto the array later using the $arr[] = $val syntax.

Download  Run Code

 
To insert a key and value pair into an associative array, you can use the $arr[$key] = $val syntax:

Download  Run Code

That’s all about creating and initializing an array in PHP.