Question
How to Pass Arrays in a Query String in PHP and JavaScript
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=bookspage=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:
- Repeated parameter names
?tag=php&tag=javascript&tag=url
- Bracket notation often used by PHP-style backends
?tag[]=php&tag[]=javascript&tag[]=url
- Indexed bracket notation
?tag[0]=php&tag[1]=javascript&tag[2]=url
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.
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' =>
]
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
URLSearchParamsreads the query string.- It sees three pairs:
color=redcolor=bluepage=2
params.get('color')returns the first matching value:
"red"
params.getAll('color')returns values for that key:
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.
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:
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:
Comparisons
| Approach | Example | Pros | Cons | Best fit |
|---|---|---|---|---|
| Repeated keys | ?tag=php&tag=js | Simple, common, works well with URL standards and JS getAll() | Some backends do not automatically build arrays | General APIs and frontend filtering |
| Bracket notation | ?tag[]=php&tag[]=js | Very convenient in PHP | Not universally special outside PHP-style parsers | PHP applications and form handling |
| Indexed brackets | ?tag[0]=php&tag[1]=js | Preserves explicit indexes | More verbose | When order/index matters |
| Comma-separated string |
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:
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.
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.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.