Introduction
Associative arrays in PHP store multiple values using named keys instead of numeric indexes. They make it easy to manage structured data such as employee details, student records, and product information. In this tutorial, you will learn to create, access, update, add, remove, and sort associative array elements through practical PHP examples.
Question 1: Create an Associative Array of Employee Details
Problem Statement
Create an associative array containing an employee’s ID, name, department, and salary. Display all employee details using print_r().
PHP Solution
<?php
$employee = [
"id" => 101,
"name" => "Rahul",
"department" => "IT",
"salary" => 45000
];
print_r($employee);
?>
Sample Output
Array
(
[id] => 101
[name] => Rahul
[department] => IT
[salary] => 45000
)
Explanation
$employeestores employee information.- Each value is associated with a named key.
"id"is a key, and101is its value.print_r()displays all keys and values.
Concepts Covered
- Associative array creation
- Key-value pairs
print_r()function
Question 2: Access Values Using Associative Array Keys
Problem Statement
Create an associative array containing student details. Display the student’s name, course, and marks using their keys.
PHP Solution
<?php
$student = [
"roll_no" => 25,
"name" => "Priya",
"course" => "PHP",
"marks" => 92
];
echo "Student Name: " . $student["name"] . "\n";
echo "Course: " . $student["course"] . "\n";
echo "Marks: " . $student["marks"];
?>
Sample Output
Student Name: Priya
Course: PHP
Marks: 92
Explanation
$student["name"]accesses the student’s name.$student["course"]accesses the course.$student["marks"]accesses the marks.- Associative arrays use named keys instead of numeric positions.
Concepts Covered
- Accessing array values
- Associative array keys
- Array element retrieval
Question 3: Update Values in an Associative Array
Problem Statement
Create an associative array containing employee details. Update the employee’s department from Sales to Marketing and salary from ₹35,000 to ₹42,000.
PHP Solution
<?php
$employee = [
"id" => 102,
"name" => "Amit",
"department" => "Sales",
"salary" => 35000
];
$employee["department"] = "Marketing";
$employee["salary"] = 42000;
print_r($employee);
?>
Sample Output
Array
(
[id] => 102
[name] => Amit
[department] => Marketing
[salary] => 42000
)
Explanation
$employee["department"]refers to the department value.- Assigning
"Marketing"replaces the previous department. $employee["salary"]updates the employee’s salary.- Other key-value pairs remain unchanged.
Concepts Covered
- Updating associative array values
- Key-based assignment
- Modifying array elements
Question 4: Add New Elements to an Associative Array
Problem Statement
Create an associative array containing product ID, product name, and price. Add two new elements: category and stock quantity.
PHP Solution
<?php
$product = [
"product_id" => 501,
"product_name" => "Laptop",
"price" => 55000
];
$product["category"] = "Electronics";
$product["stock"] = 15;
print_r($product);
?>
Sample Output
Array
(
[product_id] => 501
[product_name] => Laptop
[price] => 55000
[category] => Electronics
[stock] => 15
)
Explanation
- The original array contains three elements.
$product["category"]adds a new key-value pair.$product["stock"]adds another element.- PHP automatically stores each new value with its specified key.
Concepts Covered
- Adding associative array elements
- Named keys
- Key-value assignment
Question 5: Remove an Element Using unset()
Problem Statement
Create an associative array containing customer details. Remove the customer’s email address using unset() and display the remaining information.
PHP Solution
<?php
$customer = [
"customer_id" => 201,
"name" => "Neha",
"email" => "neha@example.com",
"city" => "Delhi",
"phone" => "9876543210"
];
unset($customer["email"]);
print_r($customer);
?>
Sample Output
Array
(
[customer_id] => 201
[name] => Neha
[city] => Delhi
[phone] => 9876543210
)
Explanation
unset()removes the specified array element.$customer["email"]identifies the email key.- The email address is removed from the array.
- All other customer details remain available.
Concepts Covered
- Removing associative array elements
unset()function- Key-based element deletion
Question 6: Display Associative Array Using foreach
Problem Statement
Create an associative array containing five department names and their monthly budgets. Display each department with its budget using a foreach loop.
PHP Solution
<?php
$budgets = [
"HR" => 50000,
"Sales" => 120000,
"IT" => 150000,
"Marketing" => 80000,
"Finance" => 70000
];
foreach ($budgets as $department => $budget) {
echo $department . " Budget: ₹" . $budget . "\n";
}
?>
Sample Output
HR Budget: ₹50000
Sales Budget: ₹120000
IT Budget: ₹150000
Marketing Budget: ₹80000
Finance Budget: ₹70000
Explanation
$budgetsstores department names as keys.- Each department has a corresponding budget.
foreachaccesses every key-value pair.$departmentstores the current key.$budgetstores the corresponding value.
Concepts Covered
- Associative array traversal
foreachloop- Key-value iteration
Question 7: Check Whether a Key Exists Using array_key_exists()
Problem Statement
Create an associative array containing employee details. Check whether the salary and bonus keys exist in the array using array_key_exists().
PHP Solution
<?php
$employee = [
"id" => 103,
"name" => "Rohit",
"department" => "HR",
"salary" => 40000
];
if (array_key_exists("salary", $employee)) {
echo "Salary key exists.\n";
} else {
echo "Salary key does not exist.\n";
}
if (array_key_exists("bonus", $employee)) {
echo "Bonus key exists.";
} else {
echo "Bonus key does not exist.";
}
?>
Sample Output
Salary key exists.
Bonus key does not exist.
Explanation
array_key_exists()checks whether a specified key is present.- The first condition checks the
salarykey. - The second condition checks the
bonuskey. - The function returns
trueif the key exists, even if its value isnull.
Concepts Covered
array_key_exists()function- Checking array keys
- Conditional statements
Question 8: Get All Keys and Values from an Associative Array
Problem Statement
Create an associative array containing product details. Display all keys using array_keys() and all values using array_values().
PHP Solution
<?php
$product = [
"id" => 301,
"name" => "Keyboard",
"price" => 1200,
"stock" => 25
];
$keys = array_keys($product);
$values = array_values($product);
echo "Product Keys:\n";
print_r($keys);
echo "Product Values:\n";
print_r($values);
?>
Sample Output
Product Keys:
Array
(
[0] => id
[1] => name
[2] => price
[3] => stock
)
Product Values:
Array
(
[0] => 301
[1] => Keyboard
[2] => 1200
[3] => 25
)
Explanation
array_keys()returns all keys from an associative array.array_values()returns all values.- Both functions create new indexed arrays.
- The original associative array remains unchanged.
Concepts Covered
array_keys()functionarray_values()function- Extracting keys and values
Question 9: Calculate Total Salary Using an Associative Array
Problem Statement
Create an associative array containing five employees and their monthly salaries. Calculate the total salary expense using a foreach loop.
PHP Solution
<?php
$salaries = [
"Rahul" => 35000,
"Priya" => 42000,
"Amit" => 38000,
"Neha" => 45000,
"Rohit" => 40000
];
$totalSalary = 0;
foreach ($salaries as $name => $salary) {
$totalSalary += $salary;
}
echo "Total Monthly Salary: ₹" . number_format($totalSalary);
?>
Sample Output
Total Monthly Salary: ₹200,000
Explanation
- Employee names are used as array keys.
- Their monthly salaries are stored as values.
$totalSalarystarts from0.- The
foreachloop accesses every salary. - Each salary is added to the total.
number_format()displays the total with thousands separators.
Concepts Covered
- Associative arrays with numeric values
foreachloop- Total calculation
number_format()function
Question 10: Sort an Associative Array by Values Using asort()
Problem Statement
Create an associative array containing employee names and their performance scores. Sort the array in ascending order according to scores while preserving employee names as keys.
PHP Solution
<?php
$scores = [
"Rahul" => 85,
"Priya" => 95,
"Amit" => 78,
"Neha" => 90,
"Rohit" => 82
];
asort($scores);
foreach ($scores as $name => $score) {
echo $name . ": " . $score . "\n";
}
?>
Sample Output
Amit: 78
Rohit: 82
Rahul: 85
Neha: 90
Priya: 95
Explanation
$scoresstores employee names as keys and scores as values.asort()sorts the array by values in ascending order.- Employee names remain associated with their original scores.
- The
foreachloop displays the sorted results.
Concepts Covered
asort()function- Sorting associative arrays by values
- Preserving array keys
foreachloop
Key Takeaways
- Associative arrays store data using named keys and values.
- Use the
=>operator to create key-value pairs. - Access values using
$array["key"]. - Update existing values by assigning a new value to their keys.
- Add new elements by specifying new keys.
- Use
unset()to remove elements. - Use
foreachto access keys and values together. - Use
array_key_exists()to check whether a key exists. - Use
array_keys()andarray_values()to extract keys and values. - Use
asort()to sort an associative array by values while preserving keys.
Frequently Asked Questions (FAQs)
1. What is an associative array in PHP?
An associative array is an array that uses named keys instead of automatically assigned numeric indexes. Each key is connected to a value.
2. How do you create an associative array in PHP?
Use the key => value format inside square brackets.
$student = [
"name" => "Rahul",
"age" => 20,
"course" => "PHP"
];
3. How do you access an associative array value?
Use the key inside square brackets.
echo $student["name"];
Output: Rahul
4. Can we use numbers as keys in associative arrays?
Yes. PHP allows integer and string keys in arrays. However, associative arrays commonly use meaningful string keys.
5. How do you add a new key-value pair?
Assign a value to a new key.
$student["city"] = "Delhi";
6. How do you update an associative array value?
Assign a new value to an existing key.
$student["age"] = 21;
7. What is the difference between isset() and array_key_exists()?
isset() returns false when a key is missing or its value is null. array_key_exists() returns true if the key exists, even when its value is null.
8. Which loop is commonly used with associative arrays?
The foreach loop is commonly used because it can access both the key and its corresponding value.
foreach ($student as $key => $value) {
echo $key . ": " . $value . "\n";
}
9. How do you sort an associative array by values?
Use asort() for ascending order or arsort() for descending order. Both preserve the association between keys and values.
10. Can an associative array contain different data types?
Yes. An associative array can store strings, integers, floats, Boolean values, and even other arrays.
$employee = [
"name" => "Priya",
"salary" => 45000,
"active" => true
];
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
