1

I'm having a little trouble with losing my array order after using unset(). This is the code I am using.

$id = $_GET['id'];
for ($i = 0; $i < count($my_array); $i++) {
  if ($my_array[$i] == $id) {
    unset($my_array[$i]);
  }
}

Assume that $my_array has 4 items and $my_array[1] is equal to $id. After I unset that, I loop on $my_array and I get an Undefined Offset: 1 error. With print_r($my_array), I get $my_array[0], $my_array[2], and $my_array[3].

I understand perfectly why that's happening. Is there a way to re-index the array so that item 2 'drops' to item 1, and and the rest of the items respectively to the end of the array?

Something like reindex($my_array) would be sweet. I know I could run another for loop with a new array and transfer them manually, but a one step solution would be awesome. I just couldn't find anything anywhere.

2 Answers 2

3

Call array_values to reindex the array.

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

4 Comments

dude you rock. Though I had tried that already. We'll just blame this one on it being after 2 am ;) Thanks again
@Adam Well, it's past 7 am here :p I guess I'll go sleep too.
@Adam By the way, after the unset, you could iterate the now-one-element-short array with foreach. If you're reindexing because you're going to iterate with that for loop, it's unnecessary; just use foreach or reset and next.
Yeah I knew I could put in another couple of steps and do it that way, but array_values seems to be doing exactly what I needed. And yeah, 7am sounds like a nice stopping point :P
1

I just discovered you can also do a

 array_splice($ar, 0, 0);

That does the re-indexing inplace, so you don't end up with a copy of the original array.

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.