Skip to content

JavaScript and PHP handle arrays differently

Caleb Porzio edited this page Nov 1, 2022 · 9 revisions

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); ?>');

Numeric Ordered Array

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.

Associative Array

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.

Numeric Un-Ordered Array

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.

Mixed Numeric/Associative 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

Problems

Now that we understand how the PHP/JS machinery behaves, we can understand the problems it poses to Livewire.

Problem A: Checksum integrity violations

Consider a Livewire component like:

Clone this wiki locally