Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP array() Function

PHP array() Function

PHP Array Reference ManualComplete PHP Array Reference Manual

Example

Create a numeric array named $cars, assign three elements to it, and print text containing the array values:

Run Example »


Definition and Usage

The array() function is used to create an array.

In PHP, there are three types of arrays:


Syntax

Syntax of a numeric array:

array(

value1,value2,value3,etc.

);

Syntax of an associative array:

array(

key=>value,key=>value,key=>value,etc.

);

Parameters Description
key Specifies the key (numeric or string).
value Specifies the value.

Technical Details

Return Value: Returns an array of the arguments.
PHP Version: 4+
Changelog: Since PHP 5.4, you can use the short array syntax, using [] instead of array().
For example, use $cars=["Volvo","BMW"]; instead of $cars=array("Volvo","BMW");

More examples

Example 1

Create an associative array named $age:

"35","Ben"=>"37","Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old."; ?>

Run Example »

Example 2

Loop through and print the values of a numeric array:

"; } ?>

Run Example »

Example 3

Loop through and print the values of an associative array:

"35","Ben"=>"37","Joe"=>"43"); foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "
"; } ?>

Run Example »

Example 4

Create a multidimensional array:

Run Example »


PHP Array Reference ManualComplete PHP Array Reference Manual