← Back to Chapters

PHP Associative Array

? PHP Associative Array

? Quick Overview

In PHP, associative arrays are arrays that use named keys instead of numeric indexes. They are useful when you want to store data in a key-value pair format, similar to dictionaries in other languages.

? Interactive Lab: Build Your Array

Add custom keys and values to see how they are structured in an associative array.

 

Equivalent PHP Code:

$myArray = array();

? Key Concepts

  • Uses named keys instead of numbers
  • Each key maps directly to a value
  • Ideal for structured and readable data

⚡ Syntax / Theory

Associative arrays are created using the => operator:

? View Code Example
// Defining an associative array with key-value pairs
$arrayName = array(
"key1" => "value1",
"key2" => "value2",
"key3" => "value3"
);

?️ Code Example 1: Creating and Accessing

? View Code Example
// Creating an associative array and accessing a value
<?php
$age = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
echo "Peter is " . $age["Peter"] . " years old.";
?>

Live Output

Peter is 35 years old.

?️ Code Example 2: Looping with foreach

? View Code Example
// Looping through associative array using foreach
<?php
$age = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
foreach ($age as $name => $value) {
echo "$name is $value years old.
";
}
?>

?️ Code Example 3: Add & Remove Elements

? View Code Example
// Adding and removing elements in associative array
<?php
$age = array("Peter" => 35, "Ben" => 37);
$age["Joe"] = 43;
unset($age["Ben"]);
print_r($age);
?>

Live Output

Array ( [Peter] => 35 [Joe] => 43 )

?️ Code Example 4: Nested Associative Array

? View Code Example
// Nested associative array for structured data
<?php
$contacts = array(
"Peter" => array("Phone" => "123456", "Email" => "peter@example.com"),
"Ben" => array("Phone" => "987654", "Email" => "ben@example.com")
);
echo $contacts["Peter"]["Email"];
?>

Live Output

peter@example.com

? Use Cases

  • User profiles and settings
  • Configuration data
  • Database-like structured storage
  • API responses handling

✅ Tips & Best Practices

  • Use meaningful and unique keys
  • Prefer associative arrays for readable data
  • Use nested arrays for complex relationships

? Try It Yourself

  • Create an array of countries and capitals
  • Build student records with subject marks
  • Add and remove keys dynamically
  • Display data using foreach formatting