Skip to content

Instantly share code, notes, and snippets.

@thiphariel
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save thiphariel/9804677 to your computer and use it in GitHub Desktop.

Select an option

Save thiphariel/9804677 to your computer and use it in GitHub Desktop.
Insert array PHP
<?php
/**
* Insert an array in another array
* @param : (array) &$array, our main array
* @param : (array) $insert, the array we want to insert
* @param : (integer) $position, where we want to insert the array
*/
function array_insert(Array &$array, Array $insert, $position)
{
// If position is start, just merge
if (0 === $position) {
$array = array_merge($insert, $array);
} else {
// If position is end, just merge
if ($position >= (count($array) - 1)) {
$array = array_merge($array, $insert);
} else {
// Else, cut head and tail, then merge them
$head = array_slice($array, 0, $position);
$tail = array_slice($array, $position);
$array = array_merge($head, $insert, $tail);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment