PHP Tutorial - PHP array() function creates an array






In PHP, there are two types of arrays:

TypeMeaning
Indexed arraysArrays with numeric index values
Associative arraysArrays with named keys(key value pair)

The array() function is used to create an array of above types.

Syntax for numeric indexed arrays

Syntax to use array() function to create numeric indexed arrays is as follows.

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

Syntax for associative arrays

Syntax to use array() function to create associative arrays is as follows.

array(key=>value,key=>value,key=>value,etc.);
ParameterDescription
keythe key (numeric or string)
valuethe value




Example 1

Create an indexed array named $names, assign four elements to it, and then print a text containing the array values.


<?php
$names = array("Volvo","BMW","Toyota","PHP from java2s.com");
echo $names[0] . ", " . $names[1] . " and " . $names[3] . ".";
?>

The code above generates the following result.

Example 2

Creates an associative array named $age.


<?php
$age=array("PHP"=>"5","Python"=>"7","Java"=>"4");
echo "PHP is " . $age['PHP'] . " years old.";
?>

The code above generates the following result.





Example 3

Loop through and print all the values of an indexed array


<?php
$cars=array("A","B","C");
$arrlength=count($cars);

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

The code above generates the following result.

Example 4

Loop through and print all the values of an associative array.


<?php
$age=array("PHP"=>"5","Python"=>"7","Java"=>"3");

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

The code above generates the following result.

Example 5

Create a multidimensional array.


<?php
$cars=array(
  array("Name"=>"PHP","Price"=>100),
  array("Name"=>"Python","Price"=>100),
  array("Name"=>"Java","Price"=>10)
);
var_dump($cars);
?>

The code above generates the following result.