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:

Numeric Ordered Array

PHP JS
[
  0 => 'foo',
  1 => 'bar',
  2 => 'baz',
]
[
  0: 'foo',
  1: 'bar',
  2: 'baz',
]

Numeric Ordered Array

PHP JS
[
  0 => 'foo',
  1 => 'bar',
  2 => 'baz',
]
[
  0: 'foo',
  1: 'bar',
  2: 'baz',
]

Clone this wiki locally