Skip to content

Instantly share code, notes, and snippets.

@widoz
Last active October 22, 2018 14:29
Show Gist options
  • Save widoz/bea120e22673b448819cda9cfcb851fa to your computer and use it in GitHub Desktop.
Save widoz/bea120e22673b448819cda9cfcb851fa to your computer and use it in GitHub Desktop.
Array Functions
<?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