ARRAY
Php provides a language construct array() for creation of array. An array is a special variable, which can hold more than one value at a time. For example :
$days=array("sun","mon",tue","wed","thru","fri","sat");
echo $days['0']; //print sun
echo $days['1']; //print mon
print_r($days);//debug
?>
In the above example, 7 values are placed in array form sun to sat. Here element will automatic store on index 0, 1, 2, 3.....
Types of arrays:
- Indexed arrays - Arrays with numeric index
- Associative arrays - Arrays with named keys
- Multidimensional arrays - Arrays containing one or more arrays
1.Indexed arrays :
$ar=array(5,10,20,30,45,25);
$i=0;
$tot=0;
while($i<6)
{
$tot=$tot+$ar[$i];
$i++;
}
echo "Result=".$tot;
?>
Output will be 135
2.Associative array
If Associative array we create an array and associate them with own keys.
$state=array("Bihar"=>"Patna","Jharkhand"=>"Ranchi","West Bengal"=>"Kolkata","Punjab"=>"Chandigarh");
foreach($state as $k=>$v)
{
echo "$k capital is $v";
}
?>
3. Multidimensional array
A multidimensional array is an array containing one or more arrays.
Example Suppose we run a computer hardware shop and have stocks of keyboard(100), Mouse(200),Printer(20) and Monitor(20).
$stock = array
(
array("Keyboard",100),
array("Mouse",200),
array("Printer",20),
array("Monitor",10)
);
echo $stock[0][0];//will print Keyword
echo $stock[1][0];//will print Mouse
echo $stock[0][1]; //will print 100
echo $stock[1][1]; //will print 200
?>