Wikis & learning

Edit a list while preserving meaningful keys

PHP arrays can mix insertion order with numeric indexes. Removing a record can leave a gap. Decide whether later consumers expect the old keys or a fresh list.

PHP arrays can mix insertion order with numeric indexes. Removing a record can leave a gap. Decide whether later consumers expect the old keys or a fresh list.

Walkthrough

unset removes a single entry. Adding with empty brackets chooses the next integer key. array_values makes a new list with contiguous indexes, which can change how the list appears in JSON.

PHP example

<?php
$labels = ['red', 'green', 'blue'];
unset($labels[1]);
$labels[] = 'gold';
echo implode(',', array_keys($labels)), PHP_EOL;
echo json_encode(array_values($labels));

Expected output

0,2,3
["red","blue","gold"]

Change and check

Remove the last entry in the original example instead of the middle one. Inspect both the retained keys and the normalized output.