In PHP, there are two types of arrays:
Type | Meaning |
---|---|
Indexed arrays | Arrays with numeric index values |
Associative arrays | Arrays with named keys(key value pair) |
The array() function is used to create an array of above types.
Syntax to use array()
function to create numeric indexed arrays is
as follows.
array(value1,value2,value3,etc.);
Syntax to use array() function to create associative arrays is as follows.
array(key=>value,key=>value,key=>value,etc.);
Parameter | Description |
---|---|
key | the key (numeric or string) |
value | the value |
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.
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.
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.
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.
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.