Last active
January 6, 2022 02:16
-
-
Save mpyw/ee28f91e5655f8684284247fad2b3113 to your computer and use it in GitHub Desktop.
array_splice_assoc.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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