Page 1 of 1

Unexpected behaviour in array unserialization

Posted: Thu Jul 14, 2005 9:26 am
by BDKR
I am seeing something that is very strange while developing on this windows box that I haven't yet been able to duplicate elsewhere. Here is some code:

Code: Select all

while($row=$this->query->dbFetchArray('indexed'))
    {
    $association=unserialize($row[0]);
    $this->associations[]=$association[0];
    }
It's obvious that at each iteration of the loop I am adding the first (the only :roll: ) element of the array ($association) to the $this->associations array. A print_r() of the class should output something like this for the $this->associations array.

[associations] => Array
(
[0] => 2277|2623
[1] => 2431|2480
)


But instead I get...

Code: Select all

їassociations] => Array
                (
                    ї0] => 2277|2623
                    ї1] => 
                )
Where the h311 is that second element?

At each iteration of the loop, the $association var should be recreated by unserialize() correct? Well here is where it gets interesting as it appears that's not what's going on. I even added a third line to unset the $association var to ensure that it's created anew at each iteration. If you look at a var_dump of the $association var at each iteration you'll see something very strange.

Code: Select all

array(1) {
  ї0]=>
  string(9) &quote;2277|2623&quote;
}


array(1) {
  ї1]=>
  string(9) &quote;2431|2480&quote;
}
While the dump has the correct information, take a look at the element number. In the second iteration, the first element of the array is 1 instead of 0!

:evil:

This is downright strange and busts up the code as it's correct operation is predicated on the fact that at each iteration that array is only going to have one element and that element should be 0. Not an incrementing value.

If you don't know what I mean by "incrementing value", let me show you an example. If I am supposed to have 4 elements in that array then the var dump will look something like...

Code: Select all

array(1) {
  ї0]=>
  string(9) &quote;2277|2623&quote;
}

array(1) {
  ї1]=>
  string(9) &quote;2431|2480&quote;
}

array(1) {
  ї2]=>
  string(9) &quote;2170|2623&quote;
}

array(1) {
  ї3]=>
  string(9) &quote;2399|2409&quote;
}
See the problem? Each one of those arrays should be fresh creations and the first element of each should be 0. Instead, it appears that unserialize() is keeping track of the array offset and incrementing it at each iteration regardless of the fact that I don't want that and more importantly DON'T EXPECT IT.

So is it just me or is there indeed something strange about this behaviour?

Posted: Fri Jul 15, 2005 6:34 am
by BDKR
No takers eh? Oh well, I coded around it.