Created
August 25, 2019 07:31
-
-
Save khanzadimahdi/86fc594649ac9f8bf6aba2e943a9940a to your computer and use it in GitHub Desktop.
php array_splice_assoc (array_splice associative)
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 | |
/** | |
PHP array_splice doesn't use associative replacement keys, so i wrote the below method to do that. | |
*/ | |
function array_splice_assoc(array &$original, int $offset, int $length = 0, $replacement = null) { | |
$slice = array_slice($original, 0, $offset, true); | |
if (!is_null($replacement)) { | |
// cast to array | |
$replacementArray = is_array($replacement) ? $replacement : [$replacement]; | |
$slice = array_merge($slice, $replacementArray); | |
} | |
$original = array_merge($slice, array_slice($original, $offset+$length, null, true)); | |
return $original; | |
} | |
/** | |
here we have 2 examples: | |
1- array splice | |
2- array associative splice | |
*/ | |
// example of array splice: | |
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); | |
$a2=array("a"=>"purple","b"=>"orange"); | |
array_splice($a1,0,2,$a2); | |
print_r($a1); // Array ( [0] => purple [1] => orange [c] => blue [d] => yellow ) | |
// example of array splice associative: | |
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); | |
$a2=array("a"=>"purple","b"=>"orange"); | |
array_splice_assoc($a1,0,2,$a2); | |
print_r($a1); // Array ( [a] => purple [b] => orange [c] => blue [d] => yellow ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment