I have an array of the form
$array = array(1 => 'a',
2 => 'b',
3 => 'c',
4 => 'd')
and I would like to create a 'hole' between 2 and 3, i.e. obtain the following array
$array = array(1 => 'a',
2 => 'b',
4 => 'c',
5 => 'd')
What do you reckon to be the best way to do this?
Holes are indices “inside” an Array that have no associated element. In other words: An Array arr is said to have a hole at index i if: 0 ≤ i < arr. length.
[, 1, , 2]; What we have above are called holes of an array, where we have nothing between the commas. An array with holes is called a sparse array. In this piece, we'll look at how holes in arrays are handled in JavaScript.
This should work:
function array_drill_hole($input, $start, $end) {
array_splice($input, $start, $end - $start, null);
return $input;
}
$array = array_combine(array_merge(range(1, 2), range(4, 5)), $array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With