Skip to content
AgileLogics
5 min read

Arrays: Indexed and Associative

Prerequisites: Loops

PHP has one array type that works as both an indexed list and an associative map (like a dictionary/hash in other languages).

$fruits = ['apple', 'banana', 'cherry']; // indexed
$user = ['name' => 'Ada', 'role' => 'admin']; // associative

echo $fruits[0];      // apple
echo $user['name'];    // Ada

foreach ($user as $key => $value) {
    echo "$key: $value";
}

Common mistakes

  • Accessing an undefined array key — this raises a warning (not a fatal error) and returns null; check with isset() or array_key_exists() first when a key might legitimately be missing.

Practice

Create an associative array with keys name and age, then print both values.

Show solution
$person = ['name' => 'Ada', 'age' => 36];
echo $person['name'];
echo $person['age'];