Rohit Pareek
Rohit Pareek

Reputation: 1563

reaarange array after deleting its element

hi i have array like $arr with 10 elements when i unset the 5 element and print the array it print he array without 5 indx. now i want to rearrange the array with 9 elements and first four values index will be same but after this values should be shifted to (previous index-1). is there any simple method is there (array function). or i have to made a complete logic for this.

Upvotes: 0

Views: 271

Answers (3)

Andy E
Andy E

Reputation: 344763

You should use array_splice, rather than unset, to remove the elements from the array. Doing so will reorder the remaining elements:

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, 1);
// $input is now array("red", "blue", "yellow")

Upvotes: 3

ircmaxell
ircmaxell

Reputation: 165271

Well, if you want to maintain order, but just want to re-index the keys, you can use the array_values() function.

$a = array(
    0 => 'a', 
    1 => 'b',
    2 => 'c', 
    3 => 'd'
);
unset($a[1]);
$a = array(
    0 => 'a', 
    2 => 'c', 
    3 => 'd'
); // Note, this is what $a is now, the re-assignment is for illustration only
$a = array_values($a);
$a = array(
    0 => 'a', 
    1 => 'c', 
    2 => 'd'
); // Note, this is what $a is now, the re-assignment is for illustration only

Upvotes: 4

Matt Lowden
Matt Lowden

Reputation: 2616

Not too sure if there's a better way but you can use array_reverse(), twice:

$array = array_reverse($array, false);
$array = array_reverse($array, false);

Upvotes: 0

Related Questions