views:

272

answers:

3
(I'm a beginner)

My script uses the standard

$c = 0;
$t = count($array);

while ($c < $t) {
  $blah = $array[$c];
  ++$c;
}

rather extensively. But I just ran into a situation where I also need array_diff and it breaks that all to hell because now the numeric keys have gaps. I'm getting Undefined offset errors all over the place.

How do I reset the numeric keys of an array? The order of the objects in the array is irrelevant.

+2  A: 

To reset the keys, you can use array_values():

$array = array_values($array);
Tatu Ulmanen
+5  A: 

You don't need to reset the keys of you array : you have to change the way you are going through it.

Instead of using a while loop and accessing the array elemnts by index, you should use a foreach loop, which will only get you elements from the array :

foreach ($array as $key => $value) {
    // $key contains the index of the current element
    // $value contains the value of the current element
}
Pascal MARTIN
+1 for you because I'll certainly use that knowledge elsewhere. But the check has to go to Tatu for hitting the bullseye. Thank you Pascal.
Andrew Heath
@Andrew : you're welcome :-) ;; Yeah, I know I wasn't really answering the question, but I thought this would be useful anyway *(and I always use foreach to loop over arrays elements)* ;; and as I saw another answer already talked about the `array_values`, I didn't put it in mine.
Pascal MARTIN
I appreciate you taking the time to answer, I really do. I'm still getting my feet wet and am recognizably in the "I've got a really kickass hammer" phase of learning to program. So again, thank you for the expansive and helpful push down the road towards more appropriate code design.
Andrew Heath
No problem about that :-)
Pascal MARTIN
A: 

Thank you Tatu.

For the lulz, I will share with you the following idiot hack I used while waiting for a sensible answer:

$badArray = array_diff($allData, $myData);

$string = implode(",",$badArray);

$dump = explode(",",$string);

$goodArray = $dump;

worked. Made me feel all dirty, but it worked.

Andrew Heath