Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Arrays in PHP always objects in JSON #11

Open
vdeurzen opened this issue Oct 16, 2014 · 1 comment
Open

Arrays in PHP always objects in JSON #11

vdeurzen opened this issue Oct 16, 2014 · 1 comment

Comments

@vdeurzen
Copy link

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?

@christopherobin
Copy link
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants