Array
Why need 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.

What is an 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

How to create array ?.

1. we can create an array by array function.

<?php
$data=array("Sun","Mon","Tue","Wed");
?>
2. we can create each array element directly.
<?php
$data[0]="Sun";
$data[1]="Mon";
$data[2]="Tue";
$data[3]="Sun";
?>
Numeric Arrays.

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):

<?php
$data=array("Sun","Mon","Tue","Wed");
for($i=0;$i<4;$i++)
{
echo $data[$i]."  ";
}
?>

Output:
Sun  Mon  Tue  Web
Associative Array

An associative array, we can assign index value for each array element.

<?php
$data=array("one"=>12,"two"=>34,"three"=>56);
foreach ($data as $value)
  {
  echo $value . " ";
  }
?>

Output:-
12 34 56
Note: foreach loop is basically for accessing each array element.
Multidimensional Arrays

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

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.

Accessing array element by list and each function

<?php
$my_array['sun']=5000;
$my_array['mon']=4000;
$my_array['tue']=9000;

while(list($key,$value)=each($my_array))
{
echo $value;
}

?>

Extracting data from an array

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>";

?>


Previous
Next