PHP Updating Arrays
Updating a list and updating a keyed record can have different consequences. Decide whether a position is disposable or a stable identifier before reindexing.
How it works
Assignment to an existing key replaces its value; assignment to a new key adds one. The empty-bracket append syntax chooses the next integer key. unset removes the key but does not promise a consecutive list afterward. array_values creates a reindexed list when that is the intended result. Reindexing an ID-keyed map would discard useful identity information.
Run it locally
Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.
php -l array-updates.php
php array-updates.phpDownload this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.
Example
<?php
declare(strict_types=1);
$queue = ["Spade", "Drill", "Rake"];
$queue[] = "Saw";
$queue[1] = "Hand drill";
unset($queue[0]);
echo array_is_list($queue) ? "List\n" : "Keys have a gap\n";
$queue = array_values($queue);
echo implode(", ", $queue), "\n";
Expected result
Keys have a gap
Hand drill, Rake, SawRemoving key zero leaves the other keys intact. array_values then deliberately discards those positions and produces a compact queue. That is acceptable because these keys were positions, not loan IDs. State this distinction in the data contract rather than depending on callers to infer it from one example.
Check the official PHP manual for detailed version and API contracts.