Last active
August 29, 2015 13:57
-
-
Save thiphariel/9804677 to your computer and use it in GitHub Desktop.
Insert array 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 | |
| /** | |
| * 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