An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
There are two ways to define associative array:
1st way :
$salary=array("Rahul"=>"50000","Amit"=>"40000","Sourav"=>"60000");
2nd way:
$salary["sumit"]="40000"; $salary["ravi"]="50000"; $salary["sourav"]="60000";
Example -1 :
<?php $salary=array("Rahul"=>"50000","Amit"=>"40000","Sourav"=>"60000"); echo "Rahul salary: ".$salary["Rahul"]."<br/>"; echo "Amit salary: ".$salary["Amit"]."<br/>"; echo "Sourav salary: ".$salary["Sourav"]."<br/>"; ?>Output:
-------------------
Rahul salary: 50000
Amit salary: 40000
Sourav salary: 60000
Example -2 :
<?php $salary["sumit"]="40000"; $salary["ravi"]="50000"; $salary["sourav"]="60000"; echo "sumit salary: ".$salary["sumit"]."<br/>"; echo "ravi salary: ".$salary["ravi"]."<br/>"; echo "sourav salary: ".$salary["sourav"]."<br/>"; ?>Output :
------------------
sumit salary: 40000
ravi salary: 50000
sourav salary: 60000
Example - 3 : (Traverse PHP Associative Array)
Lets see the below example we are using for each loop to traverse each element of associate array.
<?php $salary=array("Rahul"=>"50000","Amit"=>"40000","Sourav"=>"60000"); foreach($salary as $key => $value) { echo "Key: ".$key." Value: ".$value."<br/>"; } ?>Output:
--------------------
Key: Rahul Value: 50000
Key: Amit Value: 40000
Key: Sourav Value: 60000
Example -4 : (Count the number of elements in associate array)
Let see the below example we are using count function to get the number of elements in array.
<?php $salary=array("Rahul"=>"50000","Amit"=>"40000","Sourav"=>"60000"); echo count($salary); ?>Output:
-------------------------
3
No comments:
Post a Comment