Passing arrays as url parameter Passing arrays as url parameter arrays arrays

Passing arrays as url parameter


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.


Edit: Don't miss Stefan's solution above, which uses the very handy http_build_query() function: https://stackoverflow.com/a/1764199/179125

knittl is right on about escaping. However, there's a simpler way to do this:

$url = 'http://example.com/index.php?';$url .= 'aValues[]=' . implode('&aValues[]=', array_map('urlencode', $aValues));

If you want to do this with an associative array, try this instead:

PHP 5.3+ (lambda function)

$url = 'http://example.com/index.php?';$url .= implode('&', array_map(function($key, $val) {    return 'aValues[' . urlencode($key) . ']=' . urlencode($val);  },  array_keys($aValues), $aValues));

PHP <5.3 (callback)

function urlify($key, $val) {  return 'aValues[' . urlencode($key) . ']=' . urlencode($val);}$url = 'http://example.com/index.php?';$url .= implode('&', array_map('urlify', array_keys($aValues), $aValues));


Easiest way would be to use the serialize function.

It serializes any variable for storage or transfer. You can read about it in the php manual - serialize

The variable can be restored by using unserialize

So in the passing to the URL you use:

$url = urlencode(serialize($array))

and to restore the variable you use

$var = unserialize(urldecode($_GET['array']))

Be careful here though. The maximum size of a GET request is limited to 4k, which you can easily exceed by passing arrays in a URL.

Also, its really not quite the safest way to pass data! You should probably look into using sessions instead.