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);
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!