The array function creates a new array in PHP. We can create the following types of arrays using this function.
- Indexed arrays – Simple arrays consisting of indexes in a sequence.
- Associative arrays – Arrays having keys and corresponding values.
- Multidimensional Arrays – Arrays having one or more arrays within it.
Syntax
Syntax of PHP indexed array
array(value1, value2, value3, etc.)
Syntax of PHP associative array
array(key=>value,key=>value,key=>value,etc.)
Parameter details
Parameter | Detail |
Key | Can be string or numeric. Serve as the identifier of its value |
Value | Define the value of its key |
Example of Array function in PHP
<?php
$bikes = array("suzuki","Honda","Yamaha");
echo "I like " . $bikes[0] . ", " . $bikes[1] . " and " . $bikes[2];
?>
Create an associative array named $height
<?php
$height = array("Peter"=>"5.9","John"=>"5.7","Timothy"=>"5.6");
echo "Peter is " . $height['Peter'] . " foot long.";
?>
Loop an indexed array and print all values
<?php
$bikes = array("suzuki","Honda","Yamaha");
$arrlength=count($bikes);
for($x=0;$x<$arrlength;$x++)
{
echo $bikes[$x];
}
?>
Print all the values of an associative array in PHP
<?php
$height = array("Jawad"=>"5.9","Ahmad"=>"5.7","Abdullah"=>"5.6");
foreach($height as $x=>$height)
{
echo "Key=" . $x . ", Value=" . $height;
}
?>
Create multi-dimension array in PHP
<?php
$bikes = array
(
array("suzuki",10,30),
array("honda",100,120),
array("yamaha",150,50)
);
?>