views:

176

answers:

2

I have a method in a class that will append an item to an array member of the class. When the array member is empty (but previously had two items in it at index 1 and index 2) and I call the method, the item is inserted at index 2. Why is that? If anyone doesn't know right off the bat, I can provide MANY more details.

A: 

Are you sure the array is empty? If you print_r($obj->memberArray), do you see Array()? What is the value of count($obj->memberArray)?

Also, are the keys meaningful? If not, and you are expecting the array to be empty you should be able to safely run $obj->memberArray = array_keys($obj->memberArray) to reset the keys. I have a hunch that PHP does weird stuff when dealing with arrays with mixed (some numeric, some string) indexes, and may begin reserving indexes in that case, appending after the last numeric index. Just a hunch, haven't tested this.

eyelidlessness
+3  A: 

If I understand correctly your question, you are in this situation :

You first have an array like this one :

$data = array(
    1 => 'abcd',
    2 => 'efg',
);
var_dump($data);

You the unset all the elements :

unset($data[1], $data[2]);
var_dump($data);

And when you insert data like this :

$data[] = 'glop';
var_dump($data);

It's not put at indice 0, but 2 (actually, it's put at indice 3, it seems -- the last existing indice, plus one), which give this array in the end :

array(1) {
  [3]=>
  string(4) "glop"
}

If that is what you mean, this behaviour is described in the documentation of array :

As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero).

Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed.

(and there is an example)

Hope I understood the question right (else, can you provide an example of code, actual output, and the output you'd expect ?), and that this helps :-)

Pascal MARTIN
You understood the question perfectly and answered it as it was asked. The problem is that I didn't understand my problem fully. I even read that array documentation, but I thought something else was happening :P Thanks.
Steven Oxley