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.
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
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")
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);
精彩评论