424

Is there a standard way of passing an array through a query string?

To be clear, I have a query string with multiple values, one of which would be an array value. I want that query string value to be treated as an array- I don't want the array to be exploded so that it is indistinguishable from the other query string variables.

Also, according to this post answer, the author suggests that query string support for arrays is not defined. Is this accurate?

EDIT:

Based on @Alex's answer, there is no standard way of doing this, so my follow-up is then what is an easy way to recognize that the parameter I'm reading is an array in both PHP and Javascript?

Would it be acceptable to name multiple params the same name, and that way I would know that they belong to an array? Example:

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

Or would this be a bad practice?

Nikita Fedyashev
  • 15,938
  • 11
  • 41
  • 69
Yarin
  • 144,097
  • 139
  • 361
  • 489

11 Answers11

498

Here's what I figured out:

Submitting multi-value form fields, i.e. submitting arrays through GET/POST vars, can be done several different ways, as a standard is not necessarily spelled out.

Three possible ways to send multi-value fields or arrays would be:

  • ?cars[]=Saab&cars[]=Audi (Best way- PHP reads this into an array)
  • ?cars=Saab&cars=Audi (Bad way- PHP will only register last value)
  • ?cars=Saab,Audi (Haven't tried this)

Form Examples

On a form, multi-valued fields could take the form of a select box set to multiple:

<form> 
    <select multiple="multiple" name="cars[]"> 
        <option>Volvo</option> 
        <option>Saab</option> 
        <option>Mercedes</option> 
    </select>
</form>

(NOTE: In this case, it would be important to name the select control some_name[], so that the resulting request vars would be registered as an array by PHP)

... or as multiple hidden fields with the same name:

<input type="hidden" name="cars[]" value="Volvo">
<input type="hidden" name="cars[]" value="Saab">
<input type="hidden" name="cars[]" value="Mercedes">

NOTE: Using field[] for multiple values is really poorly documented. I don't see any mention of it in the section on multi-valued keys in Query string - Wikipedia, or in the W3C docs dealing with multi-select inputs.


UPDATE

As commenters have pointed out, this is very much framework-specific. Some examples:

Query string:

?list_a=1&list_a=2&list_a=3&list_b[]=1&list_b[]=2&list_b[]=3&list_c=1,2,3

Rails:

"list_a": "3", 
"list_b":[
    "1",
    "2",
    "3"
  ], 
"list_c": "1,2,3"

Angular:

 "list_a": [
    "1",
    "2",
    "3"
  ],
  "list_b[]": [
    "1",
    "2",
    "3"
  ],
  "list_c": "1,2,3"

(Angular discussion)

See comments for examples in node.js, Wordpress, ASP.net


Maintaining order: One more thing to consider is that if you need to maintain the order of your items (i.e. array as an ordered list), you really only have one option, which is passing a delimited list of values, and explicitly converting it to an array yourself.

Yarin
  • 144,097
  • 139
  • 361
  • 489
  • 3
    I think the reason that this functionality is not documented in general sources like Wiki or W3C is that it is not generally supported by web frameworks. PHP and I think Rails automatically convert multiple "key[]" query parameters into an array. Others don't. – Carl G Oct 25 '12 at 16:16
  • 4
    The nodejs querystring module uses the `?cars=Saab&cars=Audi` form – SystemParadox Oct 25 '13 at 11:41
  • 70
    In express (node.js), both `?cars=Saab&cars=Audi` and `?cars[]=Saab&cars[]=Audi` get turned into arrays. However, `?cars=Saab` ends up as a string, but `?cars[]=Saab` is an array with a single element. – Trevor Dixon Nov 22 '13 at 18:29
  • In the select, you miss values for options (you have got only labels). I didn't find a spec that would say that value = label if the value attribute is missing. Another thing is that "?cars=Saab&cars=Audi" is not a bad way generally. E.g. in Django (python framework), it is the right way. – clime Dec 10 '13 at 12:44
  • 5
    Can you set keys using this approach? And what about multi-dimensional arrays? – Qwerty May 23 '14 at 11:43
  • 5
    ASP.NET MVC doesn't appear to read the format `?cars[]=Saab&cars[]=Audi` There have either be no square brakets or the square brackets need indexes/ – Mr. Flibble Apr 30 '15 at 12:32
  • 2
    This is framework dependent as well. For eg, `?cars=Saab,Audi` will work for **Wordpress** but `?cars[]=Saab&cars[]=Audi` won't. – xyz Jun 02 '15 at 12:36
  • 2
    Responding to you're note, RFC 3986 says : `A host identified by an Internet Protocol literal address, version 6 [RFC3513] or later, is distinguished by enclosing the IP literal within square brackets ("[" and "]"). This is the only place where square bracket characters are allowed in the URI syntax.` https://tools.ietf.org/html/rfc3986 – tetram Aug 06 '15 at 15:51
  • @tetram, this quote is talking about ipv6 ip address formatting. this thread is about formatting of array values in the query string for which square brackets are used in an escaped format as `%5B` for `[` and `%5D` for `]`. – glasz Oct 14 '15 at 14:06
  • This quote is talking about ipv6 and square brackets... in URI syntax. And as i understand it, the array query is passed through the URL (that is an URI rigth ?). – tetram Oct 15 '15 at 19:23
  • The square bracket notation would be great if it was also generated by `http_build_query`, which unfortunately it does not. Supposedly because of dealing with arbitrary nesting. – CMCDragonkai Jul 22 '16 at 12:28
  • What do you thing: could it be an option to transform the array to an JSON string before adding this to an url? – The Bndr Aug 17 '17 at 13:39
  • This part of your answer was helpful (and I wonder where I can read the docs about this): "One more thing to consider is that if you need to maintain the order of your items (i.e. array as an ordered list), you really only have one option, which is passing a delimited list of values, and explicitly converting it to an array yourself." – Ryan Mar 17 '18 at 21:23
  • 1
    @Qwerty yes, at least with php, the key can be set in the query string, as in: ?array[keyone]=value1&array[keytwo]=value2 – timeSmith Oct 02 '18 at 17:07
  • For encoding top-level arrays in PHP: `http_build_query([['foo'=>'bar'],['baz'=>'qux']]);` gives a percent-encoded `0[foo]=bar&1[baz]=qux`. Confirming it plays well with Laravel's [input](https://laravel.com/docs/5.7/requests#retrieving-input) functionality. See [http_build_query](http://php.net/manual/en/function.http-build-query.php) and [rawurldecode](http://php.net/manual/en/function.rawurldecode.php) for more info. – Illya Moskvin Dec 11 '18 at 16:41
  • `?cars=Saab,Audi` I am using this in PHP, works fine for me. – Pardeep Poria Jan 12 '21 at 05:10
41

A query string carries textual data so there is no option but to explode the array, encode it correctly and pass it in a representational format of your choice:

p1=value1&pN=valueN...
data=[value1,...,valueN]
data={p1:value1,...,pN:valueN}

and then decode it in your server side code.

Alex K.
  • 159,548
  • 29
  • 245
  • 267
  • OK thanks for clarification. Can you see my revised question- is it necessary to do p1...pn, for keys, or can I just name multiple keys 'p', and that way I would know they all belong to same array? – Yarin Jun 05 '11 at 13:31
  • 1
    You can use the same name; http://stackoverflow.com/questions/2203430/posting-form-fields-with-same-name-attribute or just p=aa,bb,cc which is the most obvious way as Serodis commented. – Alex K. Jun 05 '11 at 13:35
  • very useful with `JSON.stringify`and `JSON.parse`! – charliebrownie Feb 01 '16 at 13:31
  • 1
    A simple and common representational format is JSON, in PHP using [`json_encode`](http://php.net/manual/en/function.json-encode.php) then [`rawurlencode`](http://php.net/manual/en/function.rawurlencode.php) and [`json_decode`](http://php.net/manual/en/function.json-decode.php) on the other page. – Edward Apr 06 '16 at 10:50
25

I don't think there's a standard.
Each web environment provides its own 'standard' for such things. Besides, the url is usually too short for anything (256 bytes limit on some browsers). Of course longer arrays/data can be send with POST requests.

However, there are some methods:

  1. There's a PHP way, which uses square brackets ([,]) in URL queries. For example a query such as ?array_name[]=item&array_name[]=item_2 has been said to work, despite being poorly documented, with PHP automatically converting it into an array. Source: https://stackoverflow.com/a/9547490/3787376

  2. Object data-interchange formats (e.g. JSON - official website, PHP documentation) can also be used if they have methods of converting variables to and from strings as JSON does.
    Also an url-encoder (available for most programming languages) is required for HTTP get requests to encode the string data correctly.

Although the "square brackets method" is simple and works, it is limited to PHP and arrays.
If other types of variable such as classes or passing variables within query strings in a language other than PHP is required, the JSON method is recommended.

Example in PHP of JSON method (method 2):

$myarray = array(2, 46, 34, "dfg");
$serialized = json_encode($myarray)
$data = 'myarray=' . rawurlencode($serialized);
// Send to page via cURL, header() or other service.

Code for receiving page (PHP):

$myarray = json_decode($_GET["myarray"]); // Or $_POST["myarray"] if a post request.
Community
  • 1
  • 1
Berry Tsakala
  • 11,390
  • 11
  • 52
  • 71
9

This works for me:

In link, to attribute has value:

to="/filter/arr?fruits=apple&fruits=banana"

Route can handle this:

path="/filter/:arr"

For Multiple arrays:

to="filter/arr?fruits=apple&fruits=banana&vegetables=potato&vegetables=onion"

Route stays same.

SCREENSHOT

enter image description here

Hamid Rohani
  • 1,370
  • 2
  • 21
  • 31
Alia
  • 657
  • 7
  • 4
9

Although there isn't a standard on the URL part, there is one standard for JavaScript. If you pass objects containing arrays to URLSearchParams, and call toString() on it, it will transform it into a comma separated list of items:

let data = {
  str: 'abc',
  arr: ['abc', 123]
}

new URLSearchParams(data).toString();
// ?str=abc&arr=abc,123 (with escaped characters)
João Haas
  • 836
  • 7
  • 11
7

I feel it would be helpful for someone who is looking for passing the array in a query string to a servlet. I tested below query string and was able to get the array values using req.getgetParameterValues(); method. Below is the query string I passed through browser.

  http://localhost:8080/ServletsTutorials/*.html? 
  myname=abc&initial=xyz&checkbox=a&checkbox=b

checkbox is my parameter array here.

vimal1083
  • 7,394
  • 6
  • 30
  • 50
vara
  • 71
  • 1
  • 1
4

I use React and Rails. I did:

js

  let params = {
    filter_array: ['A', 'B', 'C']
  }

  ...

  //transform params in URI

  Object.keys(params).map(key => {
    if (Array.isArray(params[key])) {
      return params[key].map((value) => `${key}[]=${value}`).join('&')
    }
  }
  //filter_array[]=A&filter_array[]=B&filter_array[]=C
Lini
  • 121
  • 1
  • 4
2

You mention PHP and Javascript in your question, but not in the tags. I reached this question with the intention of passing an array to an MVC.Net action.

I found the answer to my question here: the expected format is the one you proposed in your question, with multiple parameters having the same name.

Community
  • 1
  • 1
DCShannon
  • 1,975
  • 3
  • 16
  • 31
  • 2
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Andrew May 14 '15 at 19:21
  • @Andrew It's not a link only answer. "The expected format is the one you proposed in your question, with multiple parameters having the same name." – DCShannon May 14 '15 at 19:54
1

You can use http_build_query to generate a URL-encoded querystring from an array in PHP. Whilst the resulting querystring will be expanded, you can decide on a unique separator you want as a parameter to the http_build_query method, so when it comes to decoding, you can check what separator was used. If it was the unique one you chose, then that would be the array querystring otherwise it would be the normal querystrings.

keyboardP
  • 66,755
  • 13
  • 145
  • 199
0

Note that the query-string module lists the different types of array encoding it supports (https://www.npmjs.com/package/query-string):

For instance {foo: ['1', '2', '3']} can be encoded as:

'foo[]=1&foo[]=2&foo[]=3'
'foo[0]=1&foo[1]=2&foo[3]=3'
'foo=1,2,3'
'foo=1&foo=2&foo=3'
// Any custom separator can be used:
'foo=1|2|3'
// ... and more custom formats

This shows that there are many solutions adopted out there...

Will59
  • 748
  • 7
  • 15
0

Check the parse_string function http://php.net/manual/en/function.parse-str.php

It will return all the variables from a query string, including arrays.

Example from php.net:

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>
Dan Murfitt
  • 1,019
  • 2
  • 10
  • 26