22. Associative Arrays: Key-Value Pairs
Unlike indexed arrays, associative arrays use named keys (usually strings) instead of numbers. This makes the data much more meaningful and easier to work with.
Creating Associative Arrays
We use the => operator to define the key-value pairing.
php
'Michael', 'id' => 'S101', 'major' => 'Computer Science', 'gpa' => 3.8 ]; // The traditional syntax is also valid: // $student = array('name' => 'Michael', ...); ?>Accessing and Iterating
Accessing elements uses the key string within the square brackets.
php
New GPA: " . $student['gpa']; // Iterating using foreach (key and value syntax) echo "Details:
"; foreach ($student as $label => $data) { echo "" . ucfirst($label) . ": " . $data . ""; } ?>
Note: Associative arrays are fundamental for storing configuration settings, user data, and database rows in PHP.