Lesson 23 of 50 – PHP Associative Arrays
46%

PHP Associative Arrays

An associative array stores values using named keys instead of relying only on numeric indexes. It is useful for storing student details, employee records, product information, and other structured data.

1. What Is an Associative Array?

In an associative array, each value is associated with a key. We can use meaningful keys such as name, age, and course.

<?php
$student = [
    "name" => "Rahul",
    "age" => 20,
    "course" => "PHP"
];

print_r($student);
?>
Output:
Array
(
    [name] => Rahul
    [age] => 20
    [course] => PHP
)

The => operator associates each key with its corresponding value.

2. Creating an Associative Array

Use square brackets and the key => value syntax to create an associative array.

<?php
$employee = [
    "id" => 101,
    "name" => "Amit",
    "department" => "IT",
    "salary" => 25000
];

print_r($employee);
?>
Output:
Array
(
    [id] => 101
    [name] => Amit
    [department] => IT
    [salary] => 25000
)

You can also use the traditional array() syntax.

<?php
$city = array(
    "name" => "Patna",
    "state" => "Bihar"
);

print_r($city);
?>

Both syntaxes work in PHP. Square brackets are commonly used in modern PHP code.

3. Accessing Values Using Keys

Use the key inside square brackets to retrieve an associative array value.

<?php
$student = [
    "name" => "Priya",
    "age" => 21,
    "course" => "Computer Science"
];

echo $student["name"];
echo "<br>";
echo $student["age"];
echo "<br>";
echo $student["course"];
?>
Output:
Priya
21
Computer Science

Meaningful keys make code easier to understand. For example, $student["name"] clearly identifies the value being accessed.

Accessing a missing key may produce a warning. Check whether the key exists before accessing it when the key may be absent.

4. Adding and Updating Elements

Assign a value to a new key to add an element. Assigning to an existing key updates its value.

<?php
$student = [
    "name" => "Rahul",
    "age" => 20
];

// Add a new element
$student["course"] = "PHP";

// Update an existing element
$student["age"] = 21;

print_r($student);
?>
Output:
Array
(
    [name] => Rahul
    [age] => 21
    [course] => PHP
)

The key course is added, while the value associated with age changes from 20 to 21.

5. Removing Elements with unset()

The unset() function removes an element from an associative array using its key.

<?php
$student = [
    "name" => "Amit",
    "age" => 22,
    "course" => "PHP"
];

unset($student["age"]);

print_r($student);
?>
Output:
Array
(
    [name] => Amit
    [course] => PHP
)

Only the specified key and its value are removed. The other elements remain unchanged.

Check before removing a key:

<?php
$product = [
    "name" => "Keyboard",
    "price" => 500
];

if (array_key_exists("price", $product)) {
    unset($product["price"]);
}

print_r($product);
?>
Output:
Array
(
    [name] => Keyboard
)
6. Displaying Keys and Values with foreach

A foreach loop is a convenient way to display all the keys and values in an associative array.

<?php
$student = [
    "name" => "Neha",
    "age" => 19,
    "course" => "ADCA"
];

foreach ($student as $key => $value) {
    echo $key . ": " . $value . "<br>";
}
?>
Output:
name: Neha
age: 19
course: ADCA

In this example, $key stores the current key and $value stores its corresponding value.

Display only the values:

<?php
$student = [
    "name" => "Neha",
    "age" => 19,
    "course" => "ADCA"
];

foreach ($student as $value) {
    echo $value . "<br>";
}
?>
Output:
Neha
19
ADCA
7. Checking Keys and Values

PHP provides functions to check whether a key or value exists in an array.

Using array_key_exists():

<?php
$student = [
    "name" => "Rahul",
    "age" => 20
];

if (array_key_exists("name", $student)) {
    echo "Name key exists";
}
?>
Output:
Name key exists

Using isset():

<?php
$student = [
    "name" => "Rahul",
    "age" => null
];

var_dump(isset($student["name"]));
echo "<br>";
var_dump(isset($student["age"]));
echo "<br>";
var_dump(array_key_exists("age", $student));
?>
Output:
bool(true)
bool(false)
bool(true)

isset() returns false if the key is missing or its value is null. In contrast, array_key_exists() returns true when the key exists, even if its value is null.

Using in_array() to check a value:

<?php
$student = [
    "name" => "Rahul",
    "course" => "PHP"
];

if (in_array("PHP", $student, true)) {
    echo "PHP course found";
}
?>
Output:
PHP course found
8. Useful Associative Array Functions

PHP provides several useful array functions.

Function Purpose
array_keys() Returns an array containing the keys.
array_values() Returns an array containing the values.
count() Counts the top-level elements.
asort() Sorts by value while preserving keys.
ksort() Sorts by key in ascending order.

Example: Get all keys and values

<?php
$student = [
    "name" => "Priya",
    "age" => 21,
    "course" => "PHP"
];

print_r(array_keys($student));
echo "<br>";
print_r(array_values($student));
echo "<br>";
echo count($student);
?>
Output:
Array
(
    [0] => name
    [1] => age
    [2] => course
)
Array
(
    [0] => Priya
    [1] => 21
    [2] => PHP
)
3

Example: Sort by key

<?php
$marks = [
    "Science" => 85,
    "English" => 90,
    "Math" => 95
];

ksort($marks);

print_r($marks);
?>
Output:
Array
(
    [English] => 90
    [Math] => 95
    [Science] => 85
)
9. Practical Example: Student Report

An associative array can store a student's details and marks. We can then calculate the total and average of the marks.

<?php
$student = [
    "name" => "Amit Kumar",
    "course" => "ADCA",
    "English" => 80,
    "Math" => 90,
    "Computer" => 95
];

$total = $student["English"]
       + $student["Math"]
       + $student["Computer"];

$average = $total / 3;

echo "<h3>Student Report</h3>";
echo "Name: " . $student["name"] . "<br>";
echo "Course: " . $student["course"] . "<br>";
echo "English: " . $student["English"] . "<br>";
echo "Math: " . $student["Math"] . "<br>";
echo "Computer: " . $student["Computer"] . "<br>";
echo "Total Marks: " . $total . "<br>";
echo "Average Marks: " . $average;
?>
Output:
Student Report
Name: Amit Kumar
Course: ADCA
English: 80
Math: 90
Computer: 95
Total Marks: 265
Average Marks: 88.333333333333

To display the average with two decimal places, use number_format($average, 2).

Practice Assignments
  1. Create an associative array containing your name, age, city, and course.
  2. Display the student's name and course using their keys.
  3. Add a new key called mobile to an existing array.
  4. Update the value of an existing key.
  5. Remove a key using unset().
  6. Display all keys and values using foreach.
  7. Check whether a key exists using array_key_exists().
  8. Display all keys using array_keys() and all values using array_values().
  9. Create a student report and calculate the average marks.

🧠 Quick Quiz

1. Which operator associates a key with a value in an array?




2. Which function returns the keys of an array?




3. Which function checks whether a key exists even if its value is null?