What is the best way that I can pass an array as a url parameter? I was thinking if this is possible:
JavaScript
x
$aValues = array();
$url = 'http://www.example.com?aParam='.$aValues;
or how about this:
JavaScript
$url = 'http://www.example.com?aParam[]='.$aValues;
Ive read examples, but I find it messy:
JavaScript
$url = 'http://www.example.com?aParam[]=value1&aParam[]=value2&aParam[]=value3';
Advertisement
Answer
There is a very simple solution: http_build_query()
. It takes your query parameters as an associative array:
JavaScript
$data = array(
1,
4,
'a' => 'b',
'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));
will return
JavaScript
string(63) "aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d"
http_build_query()
handles all the necessary escaping for you (%5B
=> [
and %5D
=> ]
), so this string is equal to aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d
.