Insert At Array Index
This function allows the coder to insert a new array element at a given index within an existing array. The new element may be a string or another array.
<?php
/**
*
* @insert a new array member at a given index
*
* @param array $array
*
* @param mixed $new_element
*
* @param int $index
*
* @return array
*
*/
function insertArrayIndex($array, $new_element, $index) {
/*** get the start of the array ***/
$start = array_slice($array, 0, $index);
/*** get the end of the array ***/
$end = array_slice($array, $index);
/*** add the new element to the array ***/
$start[] = $new_element;
/*** glue them back together and return ***/
return array_merge($start, $end);
}
?>
Example Usage
<?php
$index = 3;
$new_element = 'steve irwin';
$array = array('platypus', 'wallaby', 'koala', 'dingo', 'wombat');
$new_array = insertArrayIndex($array, $new_element, $index);
print_r( $new_array );
?>