Arrays4 min readExamples run on PHP 8.5.10

PHP Arrays: Keys, Values and Appending

Understand PHP arrays as ordered maps, and use indexed lists without losing their existing values.

Keys and values

A PHP array is an ordered map. Keys can be integers or strings. The short syntax ["Ada", "Grace"] creates a list with integer keys starting at zero.

Append a value

$names[] = "Linus"; adds a value at the next integer key. You do not need to calculate the list length first. Appending preserves existing values and can add a duplicate.

A common mistake

Do not assume every array has consecutive integer keys. Removing an entry does not automatically turn all remaining keys into a sequence. Use explicit keys when your data represents a lookup rather than a list.

Tested examples

Minimal working example
<?php $names = ["Ada"]; $names[] = "Grace"; echo json_encode($names);
Output
["Ada","Grace"]