Re: SV: [PHP4BETA] unset() bug or feature?

From: Date: Mon, 03 Jan 2000 16:55:55 +0000
Subject: Re: SV: [PHP4BETA] unset() bug or feature?
References: 1  Groups: php.version4 
Request: Send a blank email to php-version4+get-8862@lists.php.net to get a copy of this message
Johan Ekenberg wrote: > > > > Mostly used to Perl, the result of the following code snippet > > makes me a bit > > > confused. I understand PHP makes no difference between arrays > > and hashes, > > > but in this case if feels somewhat awkward. Traversing $array, unsetting > > > each value, adding new values, renders an array which doesn't > > start at index > > > 0. Shouldn't unset() really unset the entry, making the internal array > > > pointer point to the next free place in $array (i.e. the place > > of the just > > > unset() entry)? In other words, if I unset() $array[0], why doesn't the > > > subsequent $array[] = "entry_$i" put "entry_$i" at $array[0]? > > > > As far as I undestood it (from practical code) indexed arrays are just > > a particular case for hashes/dictionaries/associative_arrays where the > > keys > > are an ints. > > Yes. But look at this: > > $array[0] = "Set"; > print count($array); // prints: 1 > unset ($array[0]); // $array now contains 0 items. > reset($array); // This doesn't help > print count($array); // prints: 0 > $array[] = "Set"; // Add to $array (which contains > _zero_ items!) > print count($array); // prints: 1 > print "$array[0]"; // prints: (nothing) > print "$array[1]"; // prints: Set > > Questions: > 1. Why isn't the internal array pointer reset when any or all items are > unset()? > 2. Why doesn't reset() reset the internal array pointer? > PHP manual: "reset() rewinds array's internal pointer to the first > element." But if you had : $array[] = "Set1"; $array[] = "Set2"; $array[] = "Set3"; then unset ($array[0]); ..in this scenario would mean all the other keys be decremented (to ``fit'' the new space) to reflect the new state which is not consistent with the notion of dictionary, where the keys aren't modifiable. Of course, in the example provided by you, it would make sense to start from zero but my guess is PHP stores the _next_ valid key(integer index), not a list of valid & spared keys (which would be more memory expensive), and since `0' was used and the array' variable is still active, the next valid key is 1'. I'm not very familiar w/ implementation internals but I guess this is a feature. -- CIMPOESU Teodor, Web Programmer @ DIGICOM S.A. Bucharest, Romania @ Internet, site development @ teo@digiro.net , +(401)-330.47.28 official home page ~ http://www.digiro.net/ Internet web page ~ http://internet.digiro.net/

« previous php.version4 (#8862) next »