PHP json_encode as object after PHP array unset()

Nanbargal

New Member
I'm experiencing odd behavior with \[code\]json_encode\[/code\] after removing a numeric array key with \[code\]unset\[/code\]. The following code should make the problem clear. I've run it from both the CLI and as an Apache mod:PHP version info:\[code\]C:\Users\usr\Desktop>php -vPHP 5.3.1 (cli) (built: Nov 20 2009 17:26:32)Copyright (c) 1997-2009 The PHP GroupZend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies\[/code\]PHP Code\[code\]<?php$a = array( new stdclass, new stdclass, new stdclass);$a[0]->abc = '123';$a[1]->jkl = '234';$a[2]->nmo = '567';printf("%s\n", json_encode($a));unset($a[1]);printf("%s\n", json_encode($a));\[/code\]Program Output\[code\]C:\Users\usr\Desktop>php test.php[{"abc":"123"},{"jkl":"234"},{"nmo":"567"}]{"0":{"abc":"123"},"2":{"nmo":"567"}}\[/code\]As you can see, the first time \[code\]$a\[/code\] is converted to JSON it's encoded as a javascript array. The second time around (after the \[code\]unset\[/code\] call) \[code\]$a\[/code\] is encoded as a javascript object. Why is this and how can I prevent it?
 
Back
Top