Latest web development tutorials

PHP array () function

PHP Array Reference Complete PHP Array Reference

Examples

Create a numeric array called $ cars, the three elements assigned to it, and prints the text contains an array of values:

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

Running instance »

Definition and Usage

array () function is used to create an array.

In PHP, there are three types of arrays:

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

grammar

Numerical array syntax:

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

Associative array syntax:

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

参数 描述
key 规定键名(数值或字符串)。
value 规定键值。

technical details

return value: Returns an array of parameters.
PHP version: 4+
Update log: Since PHP 5.4 onwards, you can use short array syntax with [] instead of the array ().
For example, $ cars = [ "Volvo", "BMW"]; instead of the $ cars = array ( "Volvo", "BMW");


More examples

Example 1

Create an associative array named $ age of:

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

Running instance »

Example 2

Traversal and print numeric array of values:

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

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

Running instance »

Example 3

Traversal and print associative array of values:

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

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

Running instance »

Example 4

Create multidimensional arrays:

<?php
// 一个二维数组
$cars=array
(
array("Volvo",100,96),
array("BMW",60,59),
array("Toyota",110,100)
);
?>

Running instance »


PHP Array Reference Complete PHP Array Reference