How to Remove Array Element and Then Re-Index Array?
I have some troubles with an array. I have one array that I want to modify like below. I want to remove element (elements) of it by index and then re-index array. Is it possible?
$foo = array(
'whatever', // [0]
'foo', // [1]
'bar' // [2]
);
$foo2 = array(
'foo', // [0], before [1]
'bar' // [1], before [2]
);
Solution 1:
unset($foo[0]); // remove item at index 0
$foo2 = array_values($foo); // 'reindex' array
Solution 2:
array_splice($array, 0, 1);
http://php.net/manual/en/function.array-splice.php
Solution 3:
You better use array_shift()
. That will return the first element of the array, remove it from the array and re-index the array. All in one efficient method.
Solution 4:
array_splice($array, array_search(array_value, $array), 1);
Solution 5:
Unset($array[0]);
Sort($array);
I don't know why this is being downvoted, but if anyone has bothered to try it, you will notice that it works.
Using sort on an array reassigns the keys of the the array. The only drawback is it sorts the values.
Since the keys will obviously be reassigned, even with array_values
, it does not matter is the values are being sorted or not.