In PHP, Associative arrays are key and value pairs. where key is any user defined string and value can be of any data type. These keys are used to access values in associative arrays.
Syntax
array_name = array("key"=>value, "key"=>value, "key"=>value);
Key | is used to access value. |
Value | is the data, which key holds in associative array. |
Create an Associative array
<?php
// Create an Associative array
$student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");
?>
Associative array is created using array() function with key=value pairs.
Above example, has $student array variable which holds three key-value pairs, which are explained in below table.
Key | Value |
---|---|
name | Vasu |
age | 17 |
class | 12th |
Access Associative arrays
Associative array can be accessed in two ways
- Traversing through loop
- with Key directly
Traversing through loop
Access key value
<?php
$student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");
foreach ($student as $k => $v) {
echo "$k : $v <br>";
}
?>
Access only Key
<?php
$student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");
foreach ($student as $k => $v) {
echo " $k <br>";
}
?>
Example explained
$student | Is an associative array |
$k | Represents all keys in $student array |
$v | Represents all related key and its value in $student array |
using array_keys() function
<?php
$student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");
$keys = array_keys($student);
foreach ($keys as $k) {
echo $k;
}
?>
Access only value
<?php
$student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");
foreach ($student as $v) {
echo " $v <br>";
}
?>
2) With Key directly
Individual key can be used to accessed value of a particular key in associative array.
<?php
$student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");
echo $student["name"] . "<br/>";
echo $student["age"] . "<br/>";
echo $student["class"] . "<br/>";
?>
Using for loop
<?php
// Create an associative array
$student = array("name"=>"Vasu", "age"=>17, "class"=>"12th");
$keys = array_keys($student);
for($i=0; $i < count($keys); $i++) {
echo $keys[$i] . ' ' . $student[$keys[$i]] . "\n";
}
?>