Example
Create an indexed array named $cars, assign three elements to it, and then print a text containing the array values:
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
OUTPUT : I like Volvo, BMW and Toyota.
Definition and Usage
The array() function is used to create an array.In PHP, there are three types of arrays:
- Indexed arrays - Arrays with numeric index
- Associative arrays - Arrays with named keys
- Multidimensional arrays - Arrays containing one or more arrays
Syntax
Syntax for indexed arrays:
array(value1,value2,value3,etc.);
array(key=>value,key=>value,key=>value,etc.);
| Parameter | Description |
|---|---|
| key | Specifies the key (numeric or string) |
| value | Specifies the value |
Technical Details
| Return Value: | Returns an array of the parameters |
|---|---|
| PHP Version: | 4 |
More Examples
Example 1
Create an associative array named $age:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
OUTPUT : Peter is 35 years old.
Example 2
Loop through and print all the values of an indexed array:
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
Volvo
BMW
Toyota
Example 3
Loop through and print all the values of an associative array:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
OUTPUT :
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
Key=Ben, Value=37
Key=Joe, Value=43