[php] How to pass an array within a query string?

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 paramater 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 bad practice?

This question is related to php arrays query-string querystringparameter

The answer is


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

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.


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.


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


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)

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

?>

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.

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.


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.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to query-string

How can I get (query string) parameters from the URL in Next.js? How to read values from the querystring with ASP.NET Core? What is the difference between URL parameters and query strings? How to get URL parameter using jQuery or plain JavaScript? How to access the GET parameters after "?" in Express? node.js http 'get' request with query string parameters Escaping ampersand in URL In Go's http package, how do I get the query string on a POST request? Append values to query string Node.js: Difference between req.query[] and req.params

Examples related to querystringparameter

How to get URL parameter using jQuery or plain JavaScript? How to pass an array within a query string?