Create a numeric array named $cars, assign three elements to it, and print the text containing the array values:
<?php$cars=array("Volvo","BMW","Toyota");echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[ 2] . ".";?>The array() function is used to create arrays.
In PHP, there are three types of arrays:
numeric array - array with numeric ID keys
Associative array - an array with specified keys, each key associated with a value
Multidimensional array - an array containing one or more arrays
Syntax for numeric arrays:
array( value1, value2, value3, etc. );
Syntax for associative arrays:
array( key=>value,key=>value,key=>value,etc. );
parameter | describe |
---|---|
key | Specifies the key name (numeric value or string). |
value | Specify key value. |
Return value: | Returns an array of parameters. |
---|---|
PHP version: | 4+ |
Update log: | Since PHP 5.4, you can use short array syntax, using [] instead of array(). For example, use $cars=["Volvo","BMW"]; instead of $cars=array("Volvo","BMW"); |
Create an associative array named $age:
<?php$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");echo "Peter is " . $age['Peter'] . " years old.";?>Iterate over and print the values of a numeric array:
<?php$cars=array("Volvo","BMW","Toyota");$arrlength=count($cars);for($x=0;$x<$arrlength;$x++) { echo $cars [$x]; echo "<br>"; }?>Iterate over and print 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>"; }?>Create a multidimensional array:
<?php// A two-dimensional array $cars=array ( array("Volvo",100,96), array("BMW",60,59), array("Toyota",110,100) );?>