Question

How to Pass Arrays in a Query String in PHP and JavaScript

phparraysquery-stringquerystringparameter

Question

I want to send an array as part of a URL query string. Is there a standard way to represent an array in a query string?

To clarify, I have several query parameters, and one of them should contain multiple values that logically belong to a single array. I do not want those values to be flattened in a way that makes them indistinguishable from the other query parameters.

I also saw a claim that query string support for arrays is not formally defined. Is that correct?

As a follow-up, if there is no universal standard, what is a simple way to recognize on the receiving side that a parameter should be treated as an array in both PHP and JavaScript?

For example, is it acceptable to repeat the same parameter name multiple times like this?

?myarray=value1&myarray=value2&myarray=value3

Would that be considered a reasonable approach, or is it bad practice?

Short Answer

By the end of this page, you will understand how query strings represent repeated values, why arrays in URLs are not universally standardized, and which patterns are commonly used in PHP and JavaScript to send and read array-like query parameters safely.

Concept

A query string is the part of a URL after the ?, such as:

/search?q=books&page=2

It is made of key-value pairs separated by &:

  • q=books
  • page=2

The important idea is this:

  • The URL standard clearly defines query strings as text data.
  • It does not define a universal built-in "array type" for query parameters.
  • That means arrays in query strings are usually represented by convention, not by a single official format understood identically everywhere.

Common conventions for arrays

Developers usually represent arrays in one of these ways:

  1. Repeated parameter names
?tag=php&tag=javascript&tag=url
  1. Bracket notation often used by PHP-style backends
?tag[]=php&tag[]=javascript&tag[]=url
  1. Indexed bracket notation
?tag[0]=php&tag[1]=javascript&tag[2]=url
  1. Comma-separated values
?tag=php,javascript,url

Each style has trade-offs. The repeated-name approach is widely used and easy to understand. The bracket style is especially common in PHP. Comma-separated values are compact, but harder if values themselves may contain commas.

Is array support standardized?

Yes and no:

  • Yes, query strings are standardized as part of URL syntax.
  • No, there is no universal array data type in the query string itself.

So the claim you saw is basically accurate: arrays are not defined in a universal way across all servers, languages, and frameworks.

Why this matters

In real applications, you often need to send multiple values for one logical field:

  • selected filters in a search page
  • multiple product IDs
  • repeated tags or categories
  • checkbox values from a form

Because the query string has no built-in array type, both the sender and receiver must agree on a format.

Mental Model

Think of a query string as a list of labeled sticky notes attached to a URL.

Each sticky note has:

  • a label (tag)
  • a value (php)

A query string does not inherently know what an array is. If you want to represent an array, you choose a pattern such as:

  • attaching several sticky notes with the same label
  • writing the label with brackets like tag[]
  • putting several values into one sticky note separated by commas

So the browser just sends text. Your server or JavaScript code decides how to interpret that text as an array.

Take Quiz

Syntax and Examples

Common syntax patterns

1. Repeated parameter names

?myarray=value1&myarray=value2&myarray=value3

This is a very common and reasonable way to represent multiple values.

2. PHP-style bracket notation

?myarray[]=value1&myarray[]=value2&myarray[]=value3

This is especially convenient in PHP because PHP can parse this into an array automatically.

3. Indexed bracket notation

?myarray[0]=value1&myarray[1]=value2&myarray[2]=value3

Useful if the exact indexes matter.

PHP examples

Reading repeated parameter names

<?php
$query = 'myarray=value1&myarray=value2&myarray=value3';
parse_str($query, $result);
var_dump($result);

In plain PHP, parse_str() typically keeps the last value for duplicate keys unless bracket syntax is used. So this may become:

[
  'myarray' => 'value3'
]

Reading PHP-style array parameters

<?php
$query = 'myarray[]=value1&myarray[]=value2&myarray[]=value3';
parse_str($query, $result);
var_dump($result);

Result:

[
  'myarray' => ['value1', 'value2', 'value3']
]

This is why bracket notation is common in PHP.

JavaScript examples

Reading repeated parameter names with URLSearchParams

const params = new URLSearchParams('?myarray=value1&myarray=value2&myarray=value3');

console.log(params.get('myarray'));     // "value1"
console.log(params.getAll('myarray'));  // ["value1", "value2", "value3"]

Reading bracket-style names

const params = new URLSearchParams('?myarray[]=value1&myarray[]=value2');

console.log(params.getAll('myarray[]'));
// ["value1", "value2"]

JavaScript does not automatically treat myarray[] as special. It is just the literal parameter name unless your code or framework adds special handling.

Recommendation

  • For PHP, myarray[]=value1&myarray[]=value2 is very convenient.
  • For general interoperability, repeating the same key is a solid choice: myarray=value1&myarray=value2.
  • If both client and server are under your control, choose one convention and use it consistently.

Step by Step Execution

Consider this JavaScript example:

const params = new URLSearchParams('?color=red&color=blue&page=2');

const firstColor = params.get('color');
const allColors = params.getAll('color');
const page = params.get('page');

console.log(firstColor);
console.log(allColors);
console.log(page);

Step by step

  1. URLSearchParams reads the query string.
  2. It sees three pairs:
    • color=red
    • color=blue
    • page=2
  3. params.get('color') returns the first matching value:
"red"
  1. params.getAll('color') returns all values for that key:
["red", "blue"]
  1. params.get('page') returns:
"2"

This example shows an important rule:

  • A repeated key can naturally represent multiple values.
  • Whether you treat that as an array depends on the parser you use.

Now compare this with PHP:

<?php
parse_str('color[]=red&color[]=blue&page=2', $result);
print_r($result);

Step by step

  1. PHP parses color[]=red.
  2. The [] tells PHP to collect values into an array.
  3. It parses color[]=blue and appends it.
  4. It parses page=2 as a normal string.
  5. The result is:
Array
(
    [color] => Array
        (
            [0] => red
            [1] => blue
        )

    [page] => 2
)

Real World Use Cases

Where this is used

Search and filtering

A shopping site may let users filter by multiple categories:

/products?category=books&category=tech

Tags or labels

A blog admin page may load posts with selected tags:

/posts?tag[]=php&tag[]=api

Multi-select form fields

A form with checkboxes often sends multiple values for the same field.

Batch operations

An admin tool may send multiple IDs:

/delete?ids[]=12&ids[]=18&ids[]=44

Frontend state in the URL

Single-page apps often store UI state in query parameters so links can be shared or bookmarked.

Why query strings are useful here

  • They are easy to bookmark.
  • They are visible and debuggable.
  • They work well for read-only filtering and navigation.

For large or sensitive arrays, query strings are usually not ideal. In those cases, a POST body is often better.

Take Quiz

Real Codebase Usage

In real projects, developers usually pick one convention based on the backend and framework.

Common patterns

1. Repeated keys for filters

APIs often accept repeated keys because they are simple and widely understood:

/users?role=admin&role=editor

In JavaScript:

const params = new URLSearchParams();
['admin', 'editor'].forEach(role => params.append('role', role));
console.log(params.toString());

2. PHP form handling with brackets

PHP developers often use bracket notation because it maps neatly into arrays:

?role[]=admin&role[]=editor

Then in PHP:

$roles = $_GET['role'] ?? [];

3. Validation and normalization

Real code often normalizes input before using it:

$roles = $_GET['role'] ?? [];
if (!is_array($roles)) {
    $roles = [$roles];
}

This is useful if your code may receive either one value or many.

4. Guard clauses

Developers often reject invalid or unexpected formats early:

const roles = params.getAll('role');
if (roles.length === 0) {
  throw new Error('At least one role is required');
}

5. Consistent serialization

In real codebases, the most important thing is consistency:

  • use one format across the app
  • document it in API docs
  • parse it the same way everywhere
  • validate the values before trusting them

Common Mistakes

1. Assuming arrays are built into query strings

Beginners sometimes expect this to work universally:

?items=[1,2,3]

This is just a string unless your code explicitly parses it.

2. Expecting PHP and JavaScript to parse formats the same way

Broken assumption:

?myarray[]=a&myarray[]=b
  • PHP treats myarray[] as an array pattern.
  • JavaScript sees the key literally as myarray[] unless you add logic.

3. Using duplicate keys without checking parser behavior

Broken PHP expectation:

parse_str('x=1&x=2&x=3', $result);
var_dump($result);

You might expect an array, but plain PHP parsing often keeps only the last value.

4. Using comma-separated values without thinking about escaping

?tags=php,javascript,node,express

This works only if commas are safe separators for your data. If a value can contain commas, parsing becomes ambiguous.

5. Forgetting URL encoding

Broken example:

?tag=c#&tag=node js

Correctly encoded:

?tag=c%23&tag=node%20js

Use built-in URL tools rather than building query strings by hand.

6. Mixing conventions in one application

For example:

?tag=php&tag=js

in one route, but:

?tag[]=php&tag[]=js

in another route.

This creates confusion and bugs. Pick one format and stay consistent.

Comparisons

ApproachExampleProsConsBest fit
Repeated keys?tag=php&tag=jsSimple, common, works well with URL standards and JS getAll()Some backends do not automatically build arraysGeneral APIs and frontend filtering
Bracket notation?tag[]=php&tag[]=jsVery convenient in PHPNot universally special outside PHP-style parsersPHP applications and form handling
Indexed brackets?tag[0]=php&tag[1]=jsPreserves explicit indexesMore verboseWhen order/index matters
Comma-separated string?tag=php,jsCompact and easy to readAmbiguous if values contain commasSmall controlled inputs
JSON in one parameter?tag=%5B%22php%22,%22js%22%5DCan represent complex structuresHarder to read, requires parsing, less common for URLsSpecial cases with controlled clients

Repeated keys vs bracket notation

QuestionRepeated keysBracket notation
Easy to readYesYes
Works naturally with JavaScript URLSearchParams.getAll()YesYes, but key name includes []
Automatically parsed as array in PHPUsually noYes
Good general-purpose API styleYesSometimes
PHP-friendlyModerateExcellent
Take Quiz

Cheat Sheet

Quick reference

There is no universal query-string array type

A query string stores text key-value pairs. Arrays are represented by convention.

Common formats

?item=a&item=b&item=c
?item[]=a&item[]=b&item[]=c
?item[0]=a&item[1]=b
?item=a,b,c

PHP

Use bracket syntax if you want automatic array parsing:

$items = $_GET['item'] ?? [];

With URL:

?item[]=a&item[]=b

JavaScript

Use URLSearchParams:

const params = new URLSearchParams(location.search);
params.get('item');      // first value
params.getAll('item');   // all values

Recommended choices

  • PHP app: item[]=a&item[]=b
  • General web/API use: item=a&item=b

Rules of thumb

  • Do not assume duplicate keys become arrays automatically.
  • Do not assume [] has special meaning in every language.
  • Prefer built-in URL encoding/parsing functions.
  • Be consistent across your application.
  • Validate and normalize input on the server.

Edge case

If you may receive either one value or many in PHP:

$items = $_GET['item'] ?? [];
if (!is_array($items)) {
    $items = [$items];
}

FAQ

Is there an official standard for arrays in query strings?

Not in a universal cross-language sense. Query strings are standardized as key-value text, but array representation is based on conventions.

Is repeating the same parameter name bad practice?

No. Repeating the same key, such as ?tag=php&tag=js, is a common and reasonable approach.

Should I use name=value1&name=value2 or name[]=value1&name[]=value2?

Use repeated keys for broad interoperability. Use bracket notation when working with PHP and you want automatic array parsing.

Does JavaScript automatically understand myarray[] as an array?

No. In JavaScript, URLSearchParams treats myarray[] as a literal parameter name unless you add your own parsing rules.

Does PHP automatically understand repeated keys as arrays?

Not usually with plain duplicate names alone. PHP reliably builds arrays when bracket notation like myarray[] is used.

Can I send complex nested arrays in a query string?

You can, but it becomes harder to read and maintain. For complex structured data, sending JSON in a request body is often better.

When should I avoid query strings for arrays?

Avoid them for large data, sensitive data, or deeply nested structures. Query strings are best for small, readable, shareable URL state.

Take Quiz

Mini Project

Description

Build a small filter URL parser that reads multiple selected categories from a query string in both JavaScript and PHP. This demonstrates the two most common approaches to array-like query parameters and shows how to normalize them into a usable array.

Goal

Create code that reads category filters from a URL and always returns them as an array.

Requirements

  • Read category values from a query string in JavaScript using URLSearchParams.
  • Read category values in PHP from a query string using bracket notation.
  • Normalize the result so your program always works with an array.
  • Print the parsed categories so the output is easy to verify.
Take Quiz

Keep learning

Related questions

View more