Consider an export configuration keyed by slot numbers 10, 20 and 30. An override that changes slot 20 should neither renumber the slots nor append a fourth label. In PHP, numeric array keys can represent either list positions or meaningful identifiers. Use an operation that preserves the intended meaning, then reject unknown keys so a typo cannot quietly add a new slot.
Prerequisites and code
Use PHP 8.3 CLI or a compatible supported PHP release. Save as layers.php. The fixture has a fixed table of slots and a patch with one replacement label. It checks results explicitly without relying on PHP assertion configuration.
<?php
function overlay(array $base, array $patch): array
{
foreach ($patch as $key => $value) {
if (!array_key_exists($key, $base)) {
throw new InvalidArgumentException("unknown slot: $key");
}
}
return array_replace($base, $patch);
}
$base = [10 => 'basic', 20 => 'standard', 30 => 'extended'];
$result = overlay($base, [20 => 'priority']);
if ($result !== [10 => 'basic', 20 => 'priority', 30 => 'extended']
|| overlay($base, []) !== $base || $base[20] !== 'standard') {
throw new RuntimeException('overlay check failed');
}
try {
overlay($base, [40 => 'typo']);
throw new RuntimeException('unknown slot was accepted');
} catch (InvalidArgumentException $e) {
echo $e->getMessage(), PHP_EOL;
}
foreach ($result as $slot => $label) {
echo "$slot $label", PHP_EOL;
}
Run the example
php layers.php
unknown slot: 40
10 basic
20 priority
30 extended
The error line is the expected result of a deliberately bad patch, not a failed run. array_replace uses a later value for the same key. It would add a key that appears only in the later array, which is why the guard runs before the replacement. An empty patch returns the baseline values and the original baseline still contains standard. The contract treats 20 as an identity rather than a vector index.
Choose a policy before extending it
The replacement is shallow. If a slot value becomes an array with a label and a timeout, replacing it with a label-only array replaces the whole value. Decide whether overrides must provide complete slot records or whether the schema permits specific field-level updates. The guard checks key membership, not the types or meanings of values. Add separate validation if your input comes from a configuration file.
If you are migrating a merge, assert the complete keyed result rather than checking only that a label appears somewhere. PHP's array merge operation renumbers numeric keys, and a left-biased array union would keep the old value on collision. If leading-zero identifiers must remain distinct, define and test their representation at ingestion instead of assuming every externally supplied ID has the same PHP array key type.