uji uji - 1 month ago 6x
PHP Question

passing arrays as url parameter

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';

Thanks in advance.


Edit: Don't miss Stefan's solution below, which uses the very handy http_build_query() function: http://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('&amp;', array_map('urlify', array_keys($aValues), $aValues));