While indexed arrays are suitable for simple numeric lists, real-world data almost always has named attributes. For example, a student record contains a name, email, roll number, and GPA. An Associative Array uses custom, descriptive string keys paired with values using the double-arrow operator (=>), creating a fast and intuitive key-value hash map.
<?php
// Creating an associative array using short syntax
$student = [
"name" => "Pooja Sharma",
"roll_no" => "BCA-2026-108",
"course" => "Bachelor of Computer Applications",
"gpa" => 3.92,
"isActive" => true
];
// Accessing elements by their named key
echo "Student Name: " . $student["name"] . "<br>";
echo "Roll Number: " . $student["roll_no"] . "<br>";
echo "Current GPA: " . $student["gpa"] . "<br>";
?>
foreach<?php
$serverConfig = [
"Host" => "127.0.0.1",
"Port" => 3306,
"Database" => "veewom_bca_db",
"Charset" => "utf8mb4"
];
echo "<table border='1' cellpadding='6'>";
foreach ($serverConfig as $setting => $value) {
echo "<tr><th>$setting</th><td>$value</td></tr>";
}
echo "</table>";
?>
Standard sort() will wipe out your named keys! For associative arrays, you must use specialized key-preserving sorting functions:
| Function | Sorted By | Direction | Key Preserved? |
|---|---|---|---|
asort($arr) |
Value | Ascending | YES |
arsort($arr) |
Value | Descending | YES |
ksort($arr) |
Key | Ascending (A-Z) | YES |
krsort($arr) |
Key | Descending (Z-A) | YES |
<?php
$marks = ["Math" => 95, "English" => 82, "PHP" => 98, "CS" => 91];
// Sort by Marks Descending (Highest score first)
arsort($marks);
print_r($marks); // PHP: 98, Math: 95, CS: 91, English: 82
// Sort by Subject Name Alphabetically
ksort($marks);
print_r($marks); // CS: 91, English: 82, Math: 95, PHP: 98
?>
High-Frequency Exam Question:
Q: What is the difference between isset($arr['key']) and array_key_exists('key', $arr)?
A: If an array element exists but its value is null (e.g. $arr = ['score' => null];), isset($arr['score']) returns false, whereas array_key_exists('score', $arr) accurately returns true.
Exercise 23.1: Create an associative array of 5 products and their prices. Sort by price in descending order and display in an HTML table.
Exercise 23.2: Write a script that extracts all array keys into an indexed array using array_keys() and all values using array_values().