← Back to Chapters

PHP Multidimensional Associative Array

? PHP Multidimensional Associative Array

? Quick Overview

A multidimensional associative array is an array where each element is an associative array itself. This allows you to store complex data structures such as records with multiple properties, employee records, products in a store, or student data.

? Key Concepts

  • Each main key maps to another associative array
  • Useful for structured and grouped data
  • Access values using multiple keys

? Syntax / Theory

The basic structure of a multidimensional associative array:

? View Code Example
// Defining a multidimensional associative array
$array = array(
"key1" => array("subkey1" => "value1", "subkey2" => "value2"),
"key2" => array("subkey1" => "value3", "subkey2" => "value4")
);

? Code Example

This example demonstrates how to create and access a multidimensional associative array:

? View Code Example
// Creating employee records using a multidimensional associative array
<?php
$employees = array(
"Peter" => array("age" => 35, "position" => "Manager", "department" => "HR"),
"John" => array("age" => 28, "position" => "Developer", "department" => "IT"),
"Doe" => array("age" => 40, "position" => "Designer", "department" => "Marketing")
);

echo $employees["Peter"]["position"];
?>

? Live Output / Explanation

The output will be Manager. The first key selects the employee name, and the second key accesses a specific property of that employee.

? Interactive Example

You can visualize this structure as a table-like hierarchy where each employee name maps to multiple attributes such as age, position, and department.

? Data Explorer

Search for an employee to see how the multidimensional keys are linked.

Main Key (Name) Subkey: Age Subkey: Position Subkey: Department
 

? Use Cases

  • Employee management systems
  • Student record databases
  • Product catalogs in e-commerce
  • Configuration data storage

✅ Tips & Best Practices

  • Use meaningful keys to improve readability
  • Keep nesting levels manageable
  • Check key existence using isset() or array_key_exists()

? Try It Yourself

  • Create a multidimensional associative array for online store products
  • Store student names, subjects, and grades, then loop using foreach
  • Add an email field to each employee and display it