How can I remove an element of an array, and reorder afterwards, without having an empty element in the array?
<?php
$c = array( 0=>12,1=>32 );
unset($c[0]); // will distort the array.
?>
Answer / Solution: array array_values ( array $input ).
<?php
$c = array( 0=>12,1=>32 );
unset($c[0]);
print_r(array_values($c));
// will print: the array cleared
?>
will return a new array with just the values, indexed linearly.
array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.
array_shift($stack);
example:
Output:
Source: http://php.net/manual/en/function.array-shift.php
Or
reset();
is also a good choiceIf you are always removing the first element, then use array_shift() instead of unset().
Otherwise, you should be able to use something like $a = array_values($a).
Another option would be array_splice(). This reorders numeric keys and appears to be a faster method if you are crunching enough data to care. But I like unset() array_values() for readability.
http://php.net/manual/en/function.array-splice.php
Speed test:
Test Code:
If you only remove the first item of the array, you could use
array_shift($c);