April 22, 2013
PHP – Can I shift an array from a specific key?
Sebastian’s Questions:
I was having a little trouble with my array in PHP.
I have the following the array:
Array
(
[0] => banana
[1] => apple
[2] => raspberry
[3] => kiwi
[4] => cherry
[5] => nuts
)
But I want to kick out ‘kiwi’ and shift all other keys up, to get the following…
Array
(
[0] => banana
[1] => apple
[2] => raspberry
[3] => cherry
[4] => nuts
)
I am sure someone here knows how to get it done, php’s shift only takes to first key and not something specific.
Thanks in advance
This is what array_splice
does for you. It even lets you insert new entries there if you so choose.
AFAIK, There is not any inbuilt function to do this, but you can create one. What you have to do is, delete an specific element and then recalculate the keys.
function a_shift($index, $array) {
unset($array[$index));
return array_values($array);
}