PHP array() function creates an array
Description
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 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.);
Parameter | Description |
---|---|
key | the key (numeric or string) |
value | the 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/*from www. jav a2 s . c o m*/
$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//w w w . j a v a 2 s . c o m
$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// w ww.ja v a2s. co m
$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.