In this tutorial, you shall learn how to create an array in PHP using array() constructor, how to create one dimensional and two dimensional arrays, with examples.

PHP Create Array

To create an array in PHP, use array() function.

We will discuss through multiple scenarios on how to create an array in PHP using array(), based on the indexing it generates for its elements.

Create Array using array() function

The syntax of array() function is

</>
Copy
array ([ mixed $... ] )

where for mixed parameter, you can provide any of these values

  • comma separated key => value pairs
  • comma separated values

array() function returns a PHP array created using the arguments passed to it.

In the following example, we will create an array containing a mix of integers and strings.

PHP Program

</>
Copy
<?php
  $arr = array(
    85,
    "apple",
    "banana"
  );
?>

In the following example, we will create an array with key => value pairs.

PHP Program

</>
Copy
<?php
  $arr = array(
    "a" => 58,
    "b" => 99,
    "c" => 41
  );
?>

Create Two Dimensional Arrays

A two dimensional array is an array in which one or more values inside the array is another array.

PHP Program

</>
Copy
<?php
  $arr = array(
    "fruits" => array("apple", "banana", "cherry"),
    "numbers" => array(54, 99, 31),
    "names" => array("Jack", "Arya", "Arjun")
  );
?>

Create PHP array with Automatic Array Index for elements

Automatic Array indexing is a mechanism in which index is generated for the array elements based on the index that we may or may not provide to the elements in the array. Based on the type of index we provide, there are many scenarios we can go through Automatic Array Indexing. We shall go through each of them with examples.

1. Index is omitted

In this scenario, we create an array of element with no index specified. In such case, PHP automatically creates an integer index for the elements. The integer index starts at 0, incrementing by one for the next elements.

In the following example, we created an array with elements, but not provided any index. So, the index of first element is 0, index of second element is 1, index of third element is 2, and so on.

PHP Program

</>
Copy
<?php
  $arr = array(
    "apple",
    "banana",
    "cherry"
  );

  foreach ($arr as $key => $value) {
    echo $key . ' - ' . $value . '<br>';
  }
?>

Program Output