Array Functions

PHP array() Function

Topic: PHP Array ReferencePrev|Next


The array() function creates an array.

It is a language construct used to represent literal arrays, it is not a regular function.

The following table summarizes the technical details of this function.

Return Value: Returns an array of the parameters.
Version: PHP 4+


The basic syntax of the array() function is given with:

array(index=>value, index=>value, ...);

The index may be of type string or integer. When indices are integers array is called indexed array, and when indices are strings array is typically called associative array.

When index is omitted or not specified, an integer index is automatically generated, starting from 0. If index is an integer, next generated index will be the bigger integer (previous index + 1). Also, if two identical index are defined, the last one overwrites the previous one.

The following example shows the array() function in action.

// Creating an array
$colors = array("red", "green", "blue", "yellow");


The array() function accepts the following parameters.

Parameter Description
index => value Specifies the index (string or integer) and its associated value.
... Specifies more indices and values.

More Examples

Here're some more examples showing how array() function is used to create arrays:

The following example shows how to create an indexed array (i.e. array with integer indices).

// Creating an indexed array
$fruits = array("apple", "banana", "orange", "mango");

The following example shows how to create an associative array (i.e. array with string indices).

// Creating an associative array
$alphabets = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "d"=>"dog");

The following example shows how to create a multidimensional array (an array of arrays).

// Creating an multidimensional array
$animals = array (
    "pet"  => array("cat", "dog", "cow", "horse"),
    "wild" => array("lion", "tiger", "zebra")
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties