Last active
December 3, 2017 10:25
-
-
Save jjgrainger/845271930a319079b74b to your computer and use it in GitHub Desktop.
Add an element to an array at a specific position
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 | |
/* | |
Array insert | |
@array the array to add an element to | |
@element the element to add to the array | |
@position the position in the array to add the element | |
*/ | |
if(!function_exists('array_insert')) { | |
function array_insert($array, $element, $position) { | |
// if the array is empty just add the element to it | |
if(empty($array)) { | |
$array[] = $element; | |
// if the position is a negative number | |
} elseif(is_numeric($position) && $position < 0) { | |
// if negative position after count | |
if(count($array) + $position < 0) { | |
$position = 0; | |
} else { | |
$position = count($array) + $position; | |
} | |
// try again with a positive position | |
$array = array_insert($array, $element, $position); | |
// if array position already set | |
} elseif(isset($array[$position])) { | |
// split array into two parts | |
$split1 = array_slice($array, 0, $position, true); | |
$split2 = array_slice($array, $position, null, true); | |
// add new array element at between two parts | |
$array = array_merge($split1, array($position => $element), $split2); | |
// if position not set add to end of array | |
} elseif(is_null($position)) { | |
$array[] = $element; | |
// if the position is not set | |
} elseif(!isset($array[$position])) { | |
$array[$position] = $element; | |
} | |
// clean up indexes | |
$array = array_values($array); | |
return $array; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment