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.
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)On a form, multi-valued fields could take the form of a select box set to multiple:
(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:
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.