Skip to content
Arrays — One Type, Two Roles
step 1/5

Reading — step 1 of 5

Learn

~1 min readArrays

PHP has one collection type — array — that does double duty as a list AND a hash table:

$nums = [10, 20, 30];                  // numeric (list)
$ages = ["Alice" => 30, "Bob" => 25]; // associative (map)

Under the hood, both are ordered hash tables. Numeric arrays just use 0, 1, 2 as keys.

$nums[] = 40;             // append
echo count($nums);         // 4
echo $nums[0];             // 10
unset($nums[0]);           // remove (leaves a sparse array — index 0 gone)

$ages["Carol"] = 40;
unset($ages["Bob"]);

Iterate with foreach:

foreach ($ages as $name => $age) {
    echo "$name: $age\n";
}

Iteration order = insertion order. Array functions: count, array_keys, array_values, in_array, array_search, sort, asort, array_merge, array_combine — too many to list.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…