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:
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.
Example
Run this code »<?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).
Example
Run this code »<?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).
Example
Run this code »<?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).
Example
Run this code »<?php
// Creating an multidimensional array
$animals = array (
"pet" => array("cat", "dog", "cow", "horse"),
"wild" => array("lion", "tiger", "zebra")
);
print_r($animals);
?>