How can I pass one or more variables of type array to another page via $_GET?
I always passed variable values in the form ?a=1&b=2&c=3
What about passing a=[1,2,3]
?
Do I need to write a for loop and append all the values?
Thanks
How can I pass one or more variables of type array to another page via $_GET?
I always passed variable values in the form ?a=1&b=2&c=3
What about passing a=[1,2,3]
?
Do I need to write a for loop and append all the values?
Thanks
You can pass an associative array to
http_build_query()
and append the resulting string as the query string to the URL. The array will automatically be parsed by PHP so$_GET
on the receiving page will contain an array.Example
this will give you:
if you want to encode the brackets also then use the below code:
Output:
Reference: http_build_query, urlencode
You can use the
[]
syntax to pass arrays through _GET:PHP understands this syntax, so
$_GET['a']
will be equal toarray(1, 2, 3)
.You can also specify keys:
Multidimentional arrays work too:
http_build_query()
does this automatically:An alternative would be to pass json encoded arrays:
And you can parse
a
withjson_decode
:And encode it again with json_encode:
Dont ever use
serialize()
for this purpose. Serialize allows to serialize objects, and there is ways to make them execute code. So you should never deserialize untrusted strings.Just repeat your
$_GET
variables like this:name=john&name=lea
This gives you an
array
.I used to believe it would be overwritten!