Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a hole in an array

Tags:

arrays

php

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?

like image 534
marcosh Avatar asked Nov 08 '13 14:11

marcosh


People also ask

What is a hole in an array?

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.

What is holes in array JavaScript?

[, 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.


2 Answers

This should work:

function array_drill_hole($input, $start, $end) {
    array_splice($input, $start, $end - $start, null);
    return $input;
}
like image 111
Amal Murali Avatar answered Sep 22 '22 04:09

Amal Murali


$array = array_combine(array_merge(range(1, 2), range(4, 5)), $array);
like image 37
aferber Avatar answered Sep 24 '22 04:09

aferber