Question

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.

Was it helpful?

Solution

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 :-)

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top