PHP array() function

Example

Create an indexed array named $cars, assign three elements to it, and then print the text containing the array values:

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

Run Instances

Definition and Usage

The array() function is used to create arrays.

In PHP, there are three types of arrays:

  • Indexed array - Array with numeric indices
  • Associative array - Array with specified keys
  • Multidimensional array - Array of one or more arrays

Description

array() creates an array with keys and values. If the key is omitted when defining the array, an integer key is generated, starting from 0 and incremented by 1.

To create an associative array with array(), you can use => to separate the key and value.

To create an empty array, do not pass any parameters to array():

$new = array();

Note:array() is actually a language construct, usually used to define literal arrays, but its usage is very similar to that of functions, so we also list it in the manual.

Syntax

The syntax of the indexed array:

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

The syntax of the associative array:

array(key=>value,key=>value,key=>value,etc.);
parameter description
key Specify the key name (numeric or string).
value Specify the key-value.

Technical Details

Returns value: Returns an array of parameters.
PHP Version: 4+
Update Log:

Starting from PHP 5.4, you can use the short array syntax, replacing array() with [].

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("Bill"=>"60","Steve"=>"56","Mark"=>"31");
echo "Bill is " . $age['Bill'] . " years old.";
?>

Run Instances

Example 2

Traverse and print the values of the indexed array:

<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
  {
  echo $cars[$x];
  echo "<br>";
  }
?>

Run Instances

Example 3

Traverse and print all values of the associative array:

<?php
$age=array("Bill"=>"60","Steve"=>"56","Mark"=>"31");
foreach($age as $x=>$x_value)
  {
  echo "Key=" . $x . ", Value=" . $x_value;
  echo "<br>";
  }
?>

Run Instances

Example 4

Create a multidimensional array:

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

Run Instances