0

I'm trying to delete the first key and value from an array while keeping the keys.

I can't seem to get this working with all the array possibilities.

Here's my $mag_cats_arr:

Array ( [6] => Science [9] => hashgraph [4] => Blockchain )

With array_slice, the keys are reset, but I need them:

$mag_cats_arr = array_slice($mag_cats_arr,1);
Array ( [0] => hashgraph [0] => Blockchain ) (Science is gone here)

How do I keep the keys when removing the first ([6] => Science) in this array?

1
  • 1
    Do you just want to remove it or do you actually want the value too? If the former, see unset(). Commented Oct 10, 2018 at 18:55

2 Answers 2

3

With array_slice, the keys are reset

array_slice() has a fourth parameter that prevents re-indexing the result array. Cf. http://php.net/array-slice

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I should read better, but now I have this: $mag_cats_arr = array_slice($mag_cats_arr,1,99,TRUE); - Is there like an infinite value for 99? For when you don't know how big the array is?
I fixed that comment above with: count($mag_cats_arr);
use NULL (as shown in the function description) or count($mag_cats_arr).
1

simple, assuming you want to remove the first element of the array and have not done a foreach or other process on it.

 unset($mag_cats_arr[key($mag_cats_array)]);

The key() function returns the first element (or wherever the pointer is) and unset removes it.

Note : if you have done some operations on the array (such as a loop) then don't forget to reset the array

3 Comments

Note : if you have done some operations then don't forget to reset the array say what?
if you run the array through any loop or you move the index pointer you need to do reset($mag_cats_array); to set it back to beginning
Not sure what you mean? reset, unset, and key are all PHP4 - 7 functions. array_slice didn't support preserve keys in PHP4 - Oh , he deleted his comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.