Passing arrays through query strings is not a standardized practice. Despite this, various techniques can be employed to simulate array behavior.
Standard Syntax:
While there is no definitive standard, using square brackets in the parameter name (e.g., myarray[]) is a common approach that allows PHP to interpret the values as an array.
Multi-Value Form Fields:
Use a multiple-select box with name[]= syntax:
<select multiple="multiple" name="cars[]"> <option>Volvo</option> <option>Saab</option> <option>Mercedes</option> </select>
Use 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">
Recognizing Arrays in Code:
PHP:
If the parameter name follows the [] syntax, PHP will automatically convert it into an array.
JavaScript:
There is no native way to identify arrays in query strings. However, it's possible to manually check the presence of multiple values with the same name:
const queryString = window.location.search; const params = new URLSearchParams(queryString); if (params.has("myarray")) { // It's an array }
Naming Multiple Params:
Using multiple parameters with the same name is acceptable but not recommended. It's not a standard practice and may cause confusion, especially if the parameters are used in multiple contexts.
Delimiting Values:
If maintaining the order of items is crucial, consider passing a delimited string and parsing it manually into an array.
The above is the detailed content of How Can I Pass Arrays in Query Strings?. For more information, please follow other related articles on the PHP Chinese website!