Lesson 2
Understanding and Using PHP Associative Arrays
Introduction

Welcome to our data structures revision! Today, we will delve deeply into PHP Associative Arrays. Much like a bookshelf, associative arrays allow you to quickly select the book (value) you desire by reading its label (key). They are vital to PHP for efficiently accessing values using keys, as well as for dynamically inserting and modifying entries. So, let's explore PHP associative arrays for a clearer understanding of these concepts.

PHP Associative Arrays

PHP associative array is a pivotal data structure that holds data as key-value pairs. Imagine storing your friend's contact info in such a way that allows you to search for your friend's name (the key) and instantly find their phone number (the value).

To define an associative array in PHP, you use the array construct or short array syntax []. For example, $contacts = ['Alice' => '123-456-7890', 'Bob' => '234-567-8901']; defines an associative array where both keys and values are strings. This array, $contacts, can store names and their corresponding phone numbers.

php
1<?php 2 3class PhoneBook { 4 private array $contacts = []; 5 6 public function addContact(string $name, string $phoneNumber): void { 7 // Method to add a contact 8 $this->contacts[$name] = $phoneNumber; 9 } 10 11 public function getPhoneNumber(string $name): string { 12 // Method to retrieve a contact's phone number, or "None" if it's not in contacts 13 if (array_key_exists($name, $this->contacts)) { 14 return $this->contacts[$name]; 15 } 16 return "None"; 17 } 18} 19 20// Create a PhoneBook instance 21$phoneBook = new PhoneBook(); 22 23// Add contacts 24$phoneBook->addContact("Alice", "123-456-7890"); 25$phoneBook->addContact("Bob", "234-567-8901"); 26echo $phoneBook->getPhoneNumber("Alice") . "\n"; // Output: 123-456-7890 27echo $phoneBook->getPhoneNumber("Bobby") . "\n"; // Output: None 28 29?>

In the above code, we create a PhoneBook class that uses an associative array to store contacts. As you can see, associative arrays simplify the processes of adding, modifying, and accessing information with unique keys.

Operations in Associative Arrays

PHP associative arrays enable a variety of operations for manipulating data, such as setting, getting, and deleting key-value pairs. Understanding these operations is crucial for efficient data handling in PHP.

To add or update entries in an associative array, you simply assign a value to a key. If the key exists, the value is updated; if not, a new key-value pair is added. This flexibility allows for dynamic updates and additions to the array without needing a predefined structure.

The array_key_exists function is used to check if a specific key exists in an array, providing a safe way to access values and prevent errors that would arise from attempting to access a nonexistent key.

Deleting an entry is done using the unset function followed by the key. This operation removes the specified key-value pair from the array, which is essential for actively managing the contents of the array.

Let’s see how these operations work in the context of a Task Manager class:

php
1<?php 2 3class TaskManager { 4 private array $tasks = []; 5 6 public function addOrUpdateTask(string $taskName, string $status): void { 7 // Add a new task or update an existing task 8 $this->tasks[$taskName] = $status; 9 } 10 11 public function getTaskStatus(string $taskName): string { 12 // Retrieve the status of a task; returns "Not Found" if the task does not exist 13 return array_key_exists($taskName, $this->tasks) ? $this->tasks[$taskName] : "Not Found"; 14 } 15 16 public function deleteTask(string $taskName): void { 17 // Removes a task using its name 18 if (array_key_exists($taskName, $this->tasks)) { 19 unset($this->tasks[$taskName]); 20 } else { 21 echo "Task '" . $taskName . "' not found.\n"; 22 } 23 } 24} 25 26// Test the TaskManager class 27$myTasks = new TaskManager(); 28$myTasks->addOrUpdateTask("Buy Milk", "Pending"); 29echo $myTasks->getTaskStatus("Buy Milk") . "\n"; // Output: Pending 30$myTasks->addOrUpdateTask("Buy Milk", "Completed"); 31echo $myTasks->getTaskStatus("Buy Milk") . "\n"; // Output: Completed 32 33$myTasks->deleteTask("Buy Milk"); 34echo $myTasks->getTaskStatus("Buy Milk") . "\n"; // Output: Not Found 35 36?>

This example showcases how to leverage associative array operations in PHP to effectively manage data by adding, updating, retrieving, and deleting entries through a simulated Task Manager application.

Looping Through Associative Arrays

PHP provides an elegant way to loop through associative arrays using foreach loops, allowing us to iterate through keys, values, or both simultaneously.

Let's explore this in our Task Manager example:

php
1<?php 2 3class TaskManager { 4 private array $tasks = []; 5 6 public function addTask(string $taskName, string $status): void { 7 $this->tasks[$taskName] = $status; 8 } 9 10 public function printAllTasks(): void { 11 // Prints all tasks' keys and values 12 foreach ($this->tasks as $taskName => $status) { 13 echo $taskName . ": " . $status . "\n"; 14 } 15 } 16} 17 18$myTasks = new TaskManager(); 19$myTasks->addTask("Buy Milk", "Pending"); 20$myTasks->addTask("Pay Bills", "Completed"); 21 22$myTasks->printAllTasks(); 23 24?>

In this case, the loop iterates through all key-value pairs in the array and prints the keys (task names) followed by the values (statuses) of the tasks using the foreach construct. Here, $taskName and $status represent the keys and values, respectively.

Nesting with Associative Arrays

Nesting in associative arrays involves storing arrays within another array. It's useful when associating multiple pieces of information with a key. Let's see how this works in a Student Database example.

php
1<?php 2 3class StudentDatabase { 4 private array $students = []; 5 6 public function addStudent(string $name, array $subjects): void { 7 // Adds a student with an array of subjects and corresponding grades 8 $this->students[$name] = $subjects; 9 } 10 11 public function getMark(string $name, string $subject): string { 12 // Retrieves the grade for a specific subject of a specific student; 13 // Returns "N/A" if the student or subject is not found 14 if (array_key_exists($name, $this->students) && array_key_exists($subject, $this->students[$name])) { 15 return $this->students[$name][$subject]; 16 } 17 return "N/A"; 18 } 19 20 public function printDatabase(): void { 21 // Prints all students with their subjects and corresponding grades 22 foreach ($this->students as $studentName => $subjects) { 23 echo "Student: " . $studentName . "\n"; // Print student name 24 foreach ($subjects as $subject => $grade) { 25 echo " Subject: " . $subject . ", Grade: " . $grade . "\n"; // Print subject and grade 26 } 27 } 28 } 29} 30 31$studentDB = new StudentDatabase(); 32$studentDB->addStudent("Alice", ["Math" => "A", "English" => "B"]); // Add a student with subjects 33 34// Retrieve and print grades for specific subjects 35echo $studentDB->getMark("Alice", "English") . "\n"; // Output: B 36echo $studentDB->getMark("Alice", "History") . "\n"; // Output: N/A 37 38// Print the complete database 39$studentDB->printDatabase(); 40/* 41Output: 42Student: Alice 43 Subject: Math, Grade: A 44 Subject: English, Grade: B 45*/ 46 47?>

By storing arrays within another array, PHP allows for a flexible way of handling complex data structures. This makes associative arrays particularly powerful for organizing data hierarchically in your applications.

Hands-on Example

Let's shift our focus to a more interactive and familiar scenario: managing a shopping cart in an online store. This hands-on example will demonstrate how associative arrays can be used to map product names to their quantities in a shopping cart. You will learn how to add products, update quantities, and retrieve the total number of items in the cart.

Here’s how you can implement and manipulate a shopping cart using a PHP associative array:

php
1<?php 2 3class ShoppingCart { 4 private array $cart = []; 5 6 public function addProduct(string $productName, int $quantity): void { 7 // Add or update the quantity of a product in the cart 8 if (array_key_exists($productName, $this->cart)) { 9 $this->cart[$productName] += $quantity; 10 } else { 11 $this->cart[$productName] = $quantity; 12 } 13 } 14 15 public function removeProduct(string $productName): void { 16 // Remove a product from the cart 17 if (array_key_exists($productName, $this->cart)) { 18 unset($this->cart[$productName]); 19 } else { 20 echo "$productName not found in your cart.\n"; 21 } 22 } 23 24 public function showCart(): void { 25 // Display the products and their quantities in the cart 26 if (empty($this->cart)) { 27 echo "Your shopping cart is empty.\n"; 28 } else { 29 foreach ($this->cart as $product => $quantity) { 30 echo $product . ": " . $quantity . "\n"; 31 } 32 } 33 } 34} 35 36$myCart = new ShoppingCart(); 37 38// Add products and update their quantities 39$myCart->addProduct("Apples", 5); 40$myCart->addProduct("Bananas", 2); 41$myCart->addProduct("Apples", 3); // Updates quantity of apples to 8 42 43// Display cart 44$myCart->showCart(); 45 46// Output: 47// Apples: 8 48// Bananas: 2 49 50// Remove a product and show the updated cart 51$myCart->removeProduct("Bananas"); 52$myCart->showCart(); 53 54// Output: 55// Apples: 8 56 57?>

This example showcases the practical application of associative arrays to manage a dynamic dataset, such as an online shopping cart. By using product names as keys and their quantities as values, we achieve efficient and flexible data manipulation. This exercise provides a solid foundation for understanding how to handle complex data structures in real-world PHP applications.

Lesson Summary and Practice

Well done! Today, we delved into PHP associative arrays and explored various operations on these arrays. We demonstrated how to efficiently manage data through examples like a phone book, task manager, student database, and a shopping cart. As you practice these concepts, you'll continue to solidify your abilities with PHP associative arrays, preparing you for more advanced programming tasks. Happy learning!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.