Indexed and associative arrays
PHP has one array type, and it does two jobs. An indexed array uses integer keys 0, 1, 2… — a list. An associative array uses keys you choose, usually strings — a dictionary or map. Under the hood both are the same thing: an ordered map from keys to values. It remembers insertion order, and keys can be ints or strings (nothing else). Write arrays with square brackets; the old array(...) syntax still works but modern code does not use it.
<?php
$langs = ['PHP', 'SQL', 'JavaScript']; // indexed: keys 0, 1, 2
$user = ['name' => 'Asha', 'age' => 31]; // associative
echo $langs[0], " and ", $langs[2], "\n";
echo $user['name'], " is ", $user['age'], "\n";
echo count($langs), " languages\n";
$user['city'] = 'Pune'; // add a key
$user['age'] = 32; // overwrite a key
print_r($user);
// keys are normalised: "5" becomes int 5, true becomes 1
$mixed = ["5" => 'a', true => 'b', 1 => 'c'];
var_dump(array_keys($mixed));PHP and JavaScript
Asha is 31
3 languages
Array
(
[name] => Asha
[age] => 32
[city] => Pune
)
array(2) {
[0]=>
int(5)
[1]=>
int(1)
}The string "5" became the int key 5, and true became the int key 1, so 'c' overwrote 'b'. A float key is cut to an int and PHP 8.1+ prints a deprecation. Stick to int and string keys and this never surprises you.
Add a 'skills' key to $user whose value is the $langs array, then print the second skill with $user['skills'][1].
print_r is the readable dump, var_dump adds types and lengths, and json_encode($arr) gives a one-line view. An indexed array with keys 0..n-1 encodes to a JSON list [...]; anything else encodes to an object {...} — which matters once you build APIs (Module 09).Warning: Undefined array key
<?php
$user = ['name' => 'Asha', 'city' => 'Pune'];
echo "Email: " . $user['email'] . "\n";Warning: Undefined array key "email" in main.php on line 3
Email: Reading a key that does not exist is not fatal in PHP: it warns, gives you null, and carries on — so the page prints an empty email and a warning. With an indexed array the message is Undefined array key 3, the classic off-by-one.
When a key is optional, give it a default with ??. When it must exist, check with isset() or array_key_exists() and handle the missing case.
<?php
$user = ['name' => 'Asha', 'city' => 'Pune'];
echo "Email: " . ($user['email'] ?? 'not given') . "\n";