-
Notifications
You must be signed in to change notification settings - Fork 0
JavaScript and PHP handle arrays differently
To understand this family of problems, you must first understand how PHP and JavaScript handle arrays:
In PHP, arrays can have numeric or string keys. In JS, arrays can only have numeric keys, and instead, you would use an object for string keys.
Let's take a look at what happens if we convert different PHP arrays to JSON and parse them into JavaScript using a PHP script like:
let jsArray = JSON.parse('<?php echo json_encode($phpArray); ?>');| PHP | JS |
|---|---|
[
0 => 'foo',
1 => 'bar',
2 => 'baz',
] |
[
'foo',
'bar',
'baz',
] |
Standard numeric/ordered arrays come to JavaScript as numeric/ordered arrays. Good so far.
| PHP | JS |
|---|---|
[
'foo' => 'bob',
'bar' => 'lob',
'baz' => 'law',
] |
{
'foo': 'bob',
'bar': 'lob',
'baz': 'law',
} |
Standard PHP associative arrays come to JavaScript as standard key-value objects. Still expected.
| PHP | JS |
|---|---|
[
0 => 'foo',
2 => 'baz',
1 => 'bar',
] |
{
'0': 'foo',
'1': 'bar',
'2': 'baz',
} |
Notice that if the array comes to JavaScript out of order, it will re-order the numeric keys and create an object instead of an array.
| PHP | JS |
|---|---|
[
'foo' => 'bob',
3 => 'lob',
'2' => 'law',
] |
{
'2': 'lob',
'3': 'bar',
'foo': 'baz',
} |
There are a few things going on here:
- JavaScript treats integer keys and numeric string keys the same. Both as numbers
- JavaScript re-orders numeric keys and places them before string keys
Now that we understand how the PHP/JS machinery behaves, we can understand the problems it poses to Livewire.
Consider a Livewire component like: