Array Functions

PHP array() Function

Topic: PHP Array ReferencePrev|Next

Description

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+

Syntax

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.

<?php
// Creating an array
$colors = array("red", "green", "blue", "yellow");
print_r($colors);
?>

Parameters

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).

<?php
// Creating an indexed array
$fruits = array("apple", "banana", "orange", "mango");
print_r($fruits);
?>

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

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

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

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