I tried to use the array_splice
strategy as described here
Insert new item in array on any position in PHP
But it doesn't work since the array is empty or the key doesn't exist. So I tried checking if the key is set first and then create it. But still it doesn't work.
If, for example, the array is empty in the first call and I want to insert elements at index 3, and I create position 3 before the array_splice
, the elements are inserted from position 0. Same happens if I don't check before using array_splice
. If the array is empty, the insert fails
function array_insert($array,$input,$index){
if(!isset($array[$index])) $array[$index] = 0;
array_splice($array,$index,0,$input);
return $array;
}
So the following call
array_insert(array(),array(36,37),3);
Generates this
array(1) { [3]=> int(0) } //var_dump before splice, after isset
array(3) { [0]=> int(0) [1]=> string(2) "36" [2]=> string(2) "37" } //var_dump after splice
What am I missing?!
@edit The expected result is: If I insert array('a','b','c') at position 3 in an empty array the resulting array should allow me to access 'a' by the key 3, 'b' by 4 etc. Not sure what is better, nulls to fill the gaps or associative keys.
@edit2
insert(array(),array(1,2),3);
array(2) { [3]=> int(1) [4]=> int(2) }
$a = array();
$a[2] = 3;
insert($a,array(1,2),1);
array(3) { 1=> int(1) [2]=> int(2) [3] => int(3) }
insert(array(1,2),array(4,5),1);
array(4) { [0]=> int(1) 1=> int(4) [2] => int(5) [3] => int(2) }
In terms of performance, what is the better choice by the way?
I think this satisfies your requirements, and I've included test cases so you can judge for yourself.