3

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

4 Answers 4

5

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Does it regenerate the keys?
@SverriM.Olsen, No kidding.
Thanks a lot :) It works out fine by e.g.: array_splice($array , 3, 1);
2
$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 ) 

Comments

2

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

4 Comments

Um... What's the purpose of array_map here?
@Kolink, It will create a new array from the values only, thus resetting the keys. And because this is part of my bigger function I forgot to remove the case for nested arrays.
Um, no it won't. It will iterate through each element of the array, and return the values of that array, throwing an error if any of the parent array's elements are not arrays... Just return array_values($arra); will do.
@Kolink, I was still completing my comment. Please read again.
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.