Logo


PHP Array Associative Array



Associative Array

Indexed arrays -Array values are keyed by integer values.
Associative arrays -Array values are keyed by string values.
These key methods can be combined as well.

Associative array = Associative word with another word.

1.The associative arrays have their index as string.
i.e. Array values are keyed by using string values called associative arrays.

2.The associative arrays store data about specific named values.

3.The associative arrays are very similar to numeric arrays but they are different in terms of their index.

4.Inside associative arrays, don’t keep double quote while printing otherwise it would not return any value.


We will use an associative array to reference the meaning of each acronym, and use the acronym as the associative array's index:
We have three associative array: MPLS (links the Multi-Protocol Label Switching), SSTP (links the Secure Socket Tunneling Protocol), and LDAP (links the Lightweight Directory Access Protocol).

Example: 1
<?php
$protocols 
= array("MPLS"=>"Multi-Protocol Label Switching",
                   
"SSTP"=>"Secure Socket Tunneling Protocol",
              
"LDAP"=>"Lightweight Directory Access Protocol");
echo 
$protocols["MPLS"]."<br />";
echo 
$protocols["SSTP"]."<br />";
echo 
$protocols["LDAP"];
?>
Output
Multi-Protocol Label Switching
Secure Socket Tunneling Protocol
Lightweight Directory Access Protocol

Another Way
Example: 2
<?php
$protocols 
= array();
$Protocols["MPLS"]= "Multi-Protocol Label Switching";
$Protocols["SSTP"]= "Secure Socket Tunneling Protocol";
$Protocols["LDAP"]= "Lightweight Directory Access Protocol";
echo 
"MPLS stands for: ".$Protocols["MPLS"]."<br />";
echo 
"SSTP stands for: ".$Protocols["SSTP"]."<br />";
echo 
"LDAP stands for: ".$Protocols["LDAP"]."<br />";
?>
Output
MPLS stands for: Multi-Protocol Label Switching
SSTP stands for: Secure Socket Tunneling Protocol
LDAP stands for: Lightweight Directory Access Protocol


To store the institutes of students in an array, we could use the students names as the keys in associative array, and the value would be their respective institute.
Example: 3
<?php
$institute 
= array(
"Oliva" => "School",
"Nicole" => "College",
"Natasha" => "University"
);
foreach (
$institute as $key=>$value) {
print(
$key": study in " $value "<br/>");
}
?>
Output
Oliva: study in School
Nicole: study in College
Natasha: study in University


Another Way
Example: 4
<?php
$people
["Oliva"] = "School";
$people["Nicole"] = "College";
$people["Natasha"] = "University";
foreach (
$people as $key=>$value) {
print(
$key": study in " $value "<br/>");
}
?>
Output
Oliva: study in School
Nicole: study in College
Natasha: study in University



If you like this Article, Share and Enjoy



See also
Array
Numeric Array
shuffle Function