Passing arrays as url parameter

arrays, php, url

Solution

There is a very simple solution: `http_build_query()`. It takes your query parameters as an associative array:

$data = array(
    1,
    4,
    'a' => 'b',
    'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));

will return

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`.

Problem

What is the best way that I can pass an array as a url parameter? I was thinking if this is possible: ``` $aValues = array(); $url = 'http://www.example.com?aParam='.$aValues; ``` or how about this: ``` $url = 'http://www.example.com?aParam[]='.$aValues; ``` Ive read examples, but I find it messy: ``` $url = 'http://www.example.com?aParam[]=value1&aParam[]=value2&aParam[]=value3'; ```

Original source

Related problems