Monday, 30 May 2011

Lesson 5 : PHP Associative array

Retweet this button on every post blogger
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

syntax :-
array( key  => value ,..... )
// key may be an integer or string.
//value may be any value of any type.

e.g.

$student  =  array("English"=>90, "Math"=>77, "Physics"=>80);

Traversing and extracting  associative array : - 


<html>
<head><title>PHP associative array</title></head>
<body>
<?php
$student  =  array("English"=>90, "Math"=>77, "Physics"=>80);

foreach ($student as $key=>$value) {
 
      echo $key." : ".$value;
}
?>
</body>
</html>



output for the above simple program is :-
English : 90
Math : 77
Physics : 80


Extraction of associative array : -


PHP extract keyword changes all keys of associative array into the variables named them with the key name and assign the value.

Exmaple ;-



<html>
<head><title>PHP associative array</title></head>
<body>
<?php
$student  =  array("English"=>90, "Math"=>77, "Physics"=>80);

extract($student);
echo "English : ".$English;
echo "<br/>";
echo " Math :".$Math;
echo "<br/>";

echo "Physics : ".$Physics;

//alternatively we can aslo use this.
echo "English : ".$student['English'];
echo "<br/>";
echo "Math : ".$student['Math'];
echo "<br/>";
echo "Physics : ".$student['Physics'];


?>
</body>
</html>


Output :- 
English : 90
Math : 77
Physics : 80