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?a
in the received page you can use:
parse_str($str, $array); var_dump($array);
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));
**in create url page**
$data = array(
'car' => 'Suzuki',
'Model' => '1976'
);
$query = http_build_query(array('myArray' => $data));
$url=urlencode($query);
echo" <p><a href=\"index2.php?data=".$url."\"> Send </a><br /> </p>";
**in received page**
parse_str($_GET['data']);
echo $myArray['car'];
echo '<br/>';
echo $myArray['model'];
This isn't a direct answer as this has already been answered, but everyone was talking about sending the data, but nobody really said what you do when it gets there, and it took me a good half an hour to work it out. So I thought I would help out here.
I will repeat this bit
$data = array(
'cat' => 'moggy',
'dog' => 'mutt'
);
$query = http_build_query(array('mydata' => $data));
$query=urlencode($query);
Obviously you would format it better than this www.someurl.com?x=$query
And to get the data back
parse_str($_GET['x']);
echo $mydata['dog'];
echo $mydata['cat'];
This is another way of solving this problem.
$data = array(
1,
4,
'a' => 'b',
'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));
I do this with serialized data base64 encoded. Best and smallest way, i guess. urlencode is to much wasting space and you have only 4k.