Last active
October 22, 2018 14:29
-
-
Save widoz/bea120e22673b448819cda9cfcb851fa to your computer and use it in GitHub Desktop.
Array Functions
This file contains 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 | |
function arrayInsertInPos( | |
$needle, | |
array &$haystack, | |
$pos, | |
$preserve = false, | |
$recursive = false | |
): array { | |
$keys = array_filter( | |
array_intersect(array_keys($needle), array_keys($haystack)), | |
'is_string' | |
); | |
if (\is_array($pos)) { | |
$key = $pos[0]; | |
$before = (isset($pos[1]) && $pos[1] === true) ?: false; | |
$pos = array_search($key, array_keys($haystack), true); | |
$pos = $before ? $pos : $pos + 1; | |
} | |
if ($keys) { | |
$arr =& $haystack; | |
if ($preserve) { | |
$arr =& $needle; | |
} | |
foreach ($keys as $key => $value) { | |
unset($arr[$value]); | |
} | |
} | |
$start = array_splice($haystack, 0, (int)$pos); | |
$func = $recursive ? 'array_merge_recursive' : 'array_merge'; | |
$haystack = $func($start, (array)$needle, $haystack); | |
return $haystack; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment