Sebastian
Sebastian

Reputation: 383

PHP - Can I shift an array from a specific key?

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

Upvotes: 3

Views: 8504

Answers (4)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

This is what array_splice does for you. It even lets you insert new entries there if you so choose.

For this specific case you use:

array_splice($array, 3, 1);

Upvotes: 5

hamon
hamon

Reputation: 109

I used this to remove keys from one array and copy to another:

$keys = [1, 3];
foreach ($keys as $index => $key) {
    if ($index != 0) {
        $key -= $index;
    }
    $newArr[] = array_splice($oldArr, $key, 1)[0];
}
return $newArr;

Upvotes: 0

Starx
Starx

Reputation: 78971

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

Upvotes: 2

Daniel
Daniel

Reputation: 4946

$array = array("banana", "apple", "raspberry", "kiwi", "cherry", "nuts");
$key = array_search('kiwi', $array);
unset($array[$key]);
$array = array_values($array);
print_r($array);

Output:
Array ( [0] => banana [1] => apple [2] => raspberry [3] => cherry [4] => nuts ) 

Upvotes: 2

Related Questions