There is a better way with
At work today, my colleague needed to add, or rather 'insert', a value into an existing array AND on a specific index.
This because we fed it into a JS table sorter, once we pulled it through
So what we really required:
We couldn't find any existing Array function at php.net, so I decided to make my own version.
At first I wanted it to work with associative arrays too, but it got complicated fast and at the time we didn't even need it; feature creep. So for now it only works with numeric array keys.
What it does..
First it checks whether the index you supplied (
$index) is available in the array (
$array), if so, dissects the array in half,
starting from the point you supplied (
$index) (there's no default function for this either, so I used array_slice).
You now have a 'first' and a 'last' array. Then you add your value (
$value) to the first array, merge both arrays back together, and you're done!
We call the function and supply it with our original array, the index after which we want our new value to be inserted and the value itself. So in the next example, we want to add the letter "D" after the "B", and this value's key is 1. So we send in the array ($array), the key (1) and our new value ("D").
So when we print_r() the
$finalArray, it looks like this: