Suppose we want to store 100 data item. So we need 100 different variable. So this is very typical work for programmer to manage 100 different variable.To overcome this problem we create a special type variable known as array.
Suppose we want to store 100 data item. So we need 100 different variable. So this is very typical work for programmer to manage 100 different variable.To overcome this problem we create a special type variable known as array.
array is a special type of variable that store one more values in one single variable. And each element in the array has its own index.
In PHP, there are three kind of arrays:
Numeric array - An array with a numeric index starting 0,1 etc.
Associative array - An array with a string index you can start like sun,mon,tue etc.
Multidimensional array - An array containing one or more arrays
1. we can create an array by array function.
A numeric array stores each array element with a numeric index.
In the following example the index are automatically assigned (the index starts at 0):
An associative array, we can assign index value for each array element.
We mantain array inside array.
<html>
<head>
<title>Two dimensional array</title>
</head>
<body bgcolor=white>
<h3>Two dimensional array</h3><br>
<table border="1">
<?php
$x=array
(
array(11,22,33),
array(44,55,66),
array(77,88,99)
);
for ($k=0;$k<3;$k++)
{
print "<tr>";
for ($j=0;$j<3;$j++)
{
echo "<td>".$x[$k][$j]."</td>";
}
print "</tr>";
}
?>
</table>
</body>
</html>
print_r() function is useful for displaying the contents of an array element.
<?php
$data=array("Sun","Mon","Tue","Wed");
print_r($data);
?>
Output:
Array ( [0] => Sun [1] => Mon [2] => Tue [3] => Wed )
Note : You can also print superglobal variable like. print_r($_POST), print_r($_REQUEST) etc.
<?php
$my_array['sun']=5000;
$my_array['mon']=4000;
$my_array['tue']=9000;
while(list($key,$value)=each($my_array))
{
echo $value;
}
?>
extract() function is use to extract data from arrays and store it in variables.
<?php
$my_array['sun']=5000;
$my_array['mon']=4000;
$my_array['tue']=9000;
extract($my_array);
echo $sun."<br>";
echo $mon."<br>";
echo $tue."<br>";
?>