HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them. Instead of accessing items by number (0, 1, 2), you access them by a meaningful string (their key).


1. The key => value Syntax

To create an associative array, you define the key and its associated value using the => operator.

<?php
    $age = [
        "Peter" => "35",
        "Ben"   => "37",
        "Joe"   => "43"
    ];
?>

2. Accessing and Modifying

Accessing data is as simple as putting the key name inside the square brackets. Note that keys are case-sensitive.

<?php
    $age = ["Peter" => "35", "Ben" => "37"];
    echo "Peter is " . $age['Peter'] . " years old.";
    
    // Updating a value
    $age['Peter'] = "36";
?>

3. Looping with Keys and Values

The foreach loop is specifically designed to handle associative arrays. You can pull out both the name of the key and the data it holds in one go.

<?php
    $user = [
        "name" => "RedoHub",
        "role" => "Admin",
        "email"=> "info@redohub.com"
    ];

    foreach($user as $key => $value) {
        echo "The user's $key is: $value <br>";
    }
?>
JSON Equivalent: Associative arrays in PHP are very similar to Objects in JavaScript or Dictionaries in Python. They are the backbone of data exchange in modern web apps.
Pro Tip: Use associative arrays whenever you have "profile" data (like name, age, city) or configuration settings where the meaning of the data is just as important as the data itself.

Key Points to Remember

  • Associative arrays use descriptive "keys" instead of numbers.
  • Use the => operator to link a key to its value.
  • Keys are case-sensitive (e.g., 'Name' and 'name' are different).
  • Use foreach($arr as $key => $val) to get both pieces of information.
  • They are ideal for structured data like user profiles and API responses.