This is sort of two questions, but there may be one overall answer for the whole problem. I have an array that I need to append onto another array. Both arrays must have specific numeric keys. My problems are:
- I need the numeric keys for the array that I am appending onto to be preserved.
- array_splice() and array_merge() won’t work to join the arrays because numeric keys in both arrays will be reset.
- I need to make the keys of the newly added elements to be n through n + x, meaning if n is 100 and x is 25, the keys for the newly added elements should be 100 through 125.
Can anyone think of a somewhat efficient way of doing this?
EDIT
For anyone curious, found a better way of adding the correct keys to the array.
// add correct keys
$array_segment = array_combine(range($offset, $offset + count($array_segment) - 1), $array_segment);
// merge arrays while maintaining keys
$first_array = $first_array + $array_segment;
I think this is a very simple solution but, if I understand well what you want, it works and it’s fast. In my opinion you can use this approach:
You can see the result here:
http://codepad.org/ogD9drpK
Another way which will avoid the foreach is to execute this instruction:
You can see the result here:
http://codepad.org/cZxCfRn6