PHP Associative Arrays

Unlike indexed arrays (which use numeric keys), associative arrays use custom keys that you define! This makes it easy to store and retrieve data using meaningful names instead of numbers. 🚀

🔹 Creating an Associative Array

Here’s how to define an associative array in PHP:

<?php
// Creating an associative array
$person = array(
    "name" => "Alice",
    "age" => 25,
    "city" => "New York"
);

// Accessing values using keys
echo "Name: " . $person["name"];
?>

Try It Now

Output: Name: Alice

Here:

  • "name", "age", and "city" are keys.
  • "Alice", 25, and "New York" are values.

🔹 Modifying & Adding Elements

You can update or add new key-value pairs anytime.

<?php
$car = array(
    "brand" => "Toyota",
    "model" => "Camry",
    "year" => 2020
);

// Modifying a value
$car["year"] = 2023;

// Adding a new key-value pair
$car["color"] = "Blue";

print_r($car);
?>

Try It Now

Output: Array ( [brand] => Toyota, [model] => Camry, [year] => 2023, [color] => Blue )


🔹 Looping Through an Associative Array

Use a foreach loop to access both keys and values.

<?php
$student = array(
    "name" => "John",
    "grade" => "A",
    "subject" => "Math"
);

foreach ($student as $key => $value) {
    echo "$key: $value <br>";
}
?>

Try It Now

Output:

name: John
grade: A
subject: Math


🔹 Checking If a Key Exists

Use array_key_exists() to check if a key exists in an array.

<?php
$user = array(
    "username" => "admin",
    "email" => "admin@example.com"
);

if (array_key_exists("email", $user)) {
    echo "Email is: " . $user["email"];
} else {
    echo "Email not found!";
}
?>

Try It Now

Output: Email is: admin@example.com


🔹 Sorting Associative Arrays

You can sort by values using asort() and by keys using ksort().

<?php
$ages = array(
    "Peter" => 35,
    "Anna" => 28,
    "John" => 40
);

asort($ages); // Sort by values

print_r($ages);
?>

Try It Now

Output: Array ( [Anna] => 28, [Peter] => 35, [John] => 40 )

Use ksort() to sort by keys.


🎯 Key Takeaways

  • Associative arrays use named keys instead of numbers.
  • Use foreach to loop through both keys & values.
  • Modify, add, and remove elements dynamically.
  • Check if a key exists using array_key_exists().
  • Sort arrays by keys (ksort()) or values (asort()).

📝 Practice Time!

Create an associative array of your favorite superheroes & their powers! 🦸‍♂️🔥