Skip to content

Instantly share code, notes, and snippets.

@mpyw
Last active January 6, 2022 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpyw/ee28f91e5655f8684284247fad2b3113 to your computer and use it in GitHub Desktop.
Save mpyw/ee28f91e5655f8684284247fad2b3113 to your computer and use it in GitHub Desktop.
array_splice_assoc.php
<?php
// https://stackoverflow.com/questions/16585502/array-splice-preserving-keys/70576992#70576992
function array_splice_assoc(array &$input, int|string $offset, ?int $length = null, $replacement = []): array
{
// Normalize offset
$offset = match (true) {
is_string($offset) => array_flip(array_keys($input))[$offset] ?? throw new OutOfBoundsException(),
$offset < 0 => count($input) + $offset,
default => $offset,
};
// Normalize length
$length = match (true) {
$length === null => count($input) - $offset,
$length < 0 => count($input) + $length - $offset,
default => $length,
};
// Manipulate each part
$before = array_slice($input, 0, $offset, true);
$removed = array_slice($input, $offset, $length, true);
$after = array_slice($input, $offset + $length, null, true);
// Merge parts, allowing the latter overrides the former
$input = array_replace($before, (array)$replacement, $after);
return $removed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment