$original = array( 'a', 'b', 'c', 'd', 'e' );
$inserted = array( 'x' ); // not necessarily an array, see manual quote
array_splice( $original, 3, 0, $inserted ); // splice in at position 3
// $original is now a b c x d e
/* insert an element after given array key
* $src = array() array to work with
* $ins = array() to insert in key=>array format
* $pos = key that $ins will be inserted after
*/
function array_insert_string_keys($src,$ins,$pos) {
$counter=1;
foreach($src as $key=>$s){
if($key==$pos){
break;
}
$counter++;
}
$array_head = array_slice($src,0,$counter);
$array_tail = array_slice($src,$counter);
$src = array_merge($array_head, $ins);
$src = array_merge($src, $array_tail);
return($src);
}
$new = array(
'title' => 'Time',
'width' => 10
);
array_splice($original,1,0,array('random_string')); // can be more items
$original[1] = $new; // replaced with actual item
function insertArrayAtPosition( $array, $insert, $position ) {
/*
$array : The initial array i want to modify
$insert : the new array i want to add, eg array('key' => 'value') or array('value')
$position : the position where the new array will be inserted into. Please mind that arrays start at 0
*/
return array_slice($array, 0, $position, TRUE) + $insert + array_slice($array, $position, NULL, TRUE);
}
/*
* Inserts a new key/value after the key in the array.
*
* @param $key
* The key to insert after.
* @param $array
* An array to insert in to.
* @param $new_key
* The key to insert.
* @param $new_value
* An value to insert.
*
* @return
* The new array if the key exists, FALSE otherwise.
*
* @see array_insert_before()
*/
function array_insert_after($key, array &$array, $new_key, $new_value) {
if (array_key_exists($key, $array)) {
$new = array();
foreach ($array as $k => $value) {
$new[$k] = $value;
if ($k === $key) {
$new[$new_key] = $new_value;
}
}
return $new;
}
return FALSE;
}
$indexnumbertoaddat // this is a variable that points to the index # where you
want the new array to be inserted
$arrayToAdd = array(array('key' => $value, 'key' => $value)); //this is the new
array and it's values that you want to add. //the key here is to write it like
array(array('key' =>, since you're adding this array inside another array. This
is the point that a lot of answer left out.
array_splice($originalArray, $indexnumbertoaddatt, 0, $arrayToAdd); //the actual
splice function. You're doing it to $originalArray, at the index # you define,
0 means you're just shifting all other index items down 1, and then you add the
new array.