php-spidermonkey icon indicating copy to clipboard operation
php-spidermonkey copied to clipboard

Arrays in PHP always objects in JSON

Open vdeurzen opened this issue 11 years ago • 1 comments

When returning an array from a PHP function, exposed to SpiderMonkey, the array is turned into a JSON object, rather than an array. Regardless of whether we are returning an associative or numeric array.

Is there any fix for this available currently or is it expected / correct behaviour?

vdeurzen avatar Oct 16 '14 15:10 vdeurzen

The issue is that PHP does not differentiate between associative and numeric arrays internally, the only way to detect it somehow is to scan the array keys and check that none of them are string and that the numeric keys are contiguous. While it is doable, performance on large arrays would be probably quite bad.

The reason is that PHP and Javascript differ in how they work with numeric arrays, see:

a = [];
a[7] = 8;
console.log(a);
// returns [ , , , , , , , 8 ]

Javascript consider arrays as contiguous values, so writing to key 7 implies to keys 0 to 6 exists and those are set to undefined automatically but in PHP no such thing happens:

$a = [];
$a[7] = 8;
var_dump($a);
// returns
// array(
//   7 => 8
// )

The reason is once again that PHP does not differentiate between numeric and associative, it just consider the integer 7 as a hash key who just happens to be an integer.

Tbh I guess a 'strict mode' could be added somehow that forces that scan in exchange of processing speed but I'm not sure if it is entirely worth it.

Another solution I had in mind at some point is that if at least 1 numeric key exists, an array is created and string keys are put as property on the array object but I remember that the SpiderMonkey API didn't like that very much.

christopherobin avatar Oct 17 '14 01:10 christopherobin