PHP array()Functions

PHP Array 参考手册Complete PHP Array Reference

Examples

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

<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Run example »

Definition and Usage

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

In PHP, there are three types of arrays:

  • Numeric array- An array with numeric ID keys
  • Associative array- An array with specified keys, each key associated with a value
  • Multidimensional array- An array containing one or more arrays

Syntax

Syntax for numeric arrays:

array(value1,value2,value3,etc.);

Syntax for associative arrays:

array(key=>value,key=>value,key=>value,etc.);

Parameter Description
key Specifies the key name (numeric or string).
value Specifies the key value.

Technical Details

Return value: Returns an array of the parameters.
PHP Version: 4+
Changelog: As of PHP 5.4, short array syntax can be used, 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:

<?php
$age=array("Peter"=>"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:

<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>

Run example »

Example 3

Loop through and print the values of an associative array:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

Run example »

Example 4

Create a multidimensional array:

<?php
// A two-dimensional array
$cars=array
(
array("Volvo",100,96),
array("BMW",60,59),
array("Toyota",110,100)
);
?>

Run example »


PHP Array 参考手册Complete PHP Array Reference Other Extensions