Beginner Fundamentals

PHP Associative Arrays

Associative arrays use named keys instead of numeric positions. This makes the data easier to read and access by meaning.

Creating an associative array

Use the key => value syntax.

<?php
$person = [
    "name" => "Carla",
    "age" => 28,
    "city" => "Lisbon"
];

Accessing values

Use the key inside square brackets.

<?php
echo $person["name"]; // Carla
echo $person["age"];  // 28

Adding or changing values

<?php
$person["email"] = "carla@example.com"; // add
$person["age"] = 29;                      // update

Looping with foreach

foreach can read both the key and the value.

<?php
foreach ($person as $key => $value) {
    echo "$key: $value\n";
}
// name: Carla
// age: 29
// city: Lisbon

Checking a key

Use isset() to verify a key exists before using it.

<?php
if (isset($person["name"])) {
    echo "Name is set";
}