views:

20

answers:

1

I'm having a little trouble with losing my array order after using unset(). Here's the code first:

$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 try to run a foreach() on $my_array and I get and Undefined Offset: 1 error. When I run print_r($my_array), I get $my_array[0], $my_array[2], and $my_array[3].

I understand perfectly why that's happening, my question is, 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  A: 

Call array_values to reindex the array.

Artefacto
dude you rock. Though I had tried that already. We'll just blame this one on it being after 2 am ;)Thanks again
Adam Tootle
@Adam Well, it's past 7 am here :p I guess I'll go sleep too.
Artefacto
@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`.
Artefacto
@Artefacto 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
Adam Tootle