PHP Arrays can store multiple values in one single variable.
In PHP, the array() function is used to create an array:
array();
There are three types of arrays:
The elements of an array can be many things other than a string or integer. You can even have objects or other arrays.
There are two ways to create indexed arrays:
$colors = array("Red", "Blue", "Green");
$colors[0] = "Red";
$colors[1] = "Blue";
$colors[2] = "Green";
Looping through an Indexed Array
We can use For loop to loop through an indexed array:
<?php
$colors = array("Red", "Blue", "Green");
$arrlength = count($colors);
for($x = 0; $x < $arrlength; $x++) {
echo $colors[$x];
echo "<br>";
}
?>
Associative array can be key => value
or simply indexed by numbers.
There are two ways to create an associative array:
$age = array("Anna"=>"19", "John"=>"18", "Peter"=>"20");
or:
$age["Anna"] = "19";
$age["John"] = "18";
$age["Peter"] = "20";
Looping Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach loop, like this:
<?php
$detail = array("name" => "Anna", "course" => "SI664");
foreach($detail as $k => $v ) {
echo "Key=",$k," Val=",$v,"\n";
}
?>
A multidimensional array is an array containing one or more arrays.
$products = array(
'paper' => array(
'copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper"),
'pens' => array(
'ball' => "Ball Point",
'hilite' => "Highlighters",
'marker' => "Markers"),
'misc' => array(
'tape' => "Sticky Tape",
'glue' => "Adhesives",
'clips' => "Paperclips")
);
echo $products["pens"]["marker"];
// Output: Markers