Passing arrays as url parameter

Viewed 326699

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';
11 Answers
 <?php
$array["a"] = "Thusitha";
$array["b"] = "Sumanadasa";
$array["c"] = "Lakmal";
$array["d"] = "Nanayakkara";

$str = serialize($array);
$strenc = urlencode($str);
print $str . "\n";
print $strenc . "\n";
?> 

print $str . "\n"; gives a:4:{s:1:"a";s:8:"Thusitha";s:1:"b";s:10:"Sumanadasa";s:1:"c";s:6:"Lakmal";s:1:"d";s:11:"Nanayakkara";} and

print $strenc . "\n"; gives

a%3A4%3A%7Bs%3A1%3A%22a%22%3Bs%3A8%3A%22Thusitha%22%3Bs%3A1%3A%22b%22%3Bs%3A10%3A%22Sumanadasa%22%3Bs%3A1%3A%22c%22%3Bs%3A6%3A%22Lakmal%22%3Bs%3A1%3A%22d%22%3Bs%3A11%3A%22Nanayakkara%22%3B%7D

So if you want to pass this $array through URL to page_no_2.php,

ex:-

$url ='http://page_no_2.php?data=".$strenc."';

To return back to the original array, it needs to be urldecode(), then unserialize(), like this in page_no_2.php:

    <?php
    $strenc2= $_GET['data'];
    $arr = unserialize(urldecode($strenc2));
    var_dump($arr);
    ?>

gives

 array(4) {
  ["a"]=>
  string(8) "Thusitha"
  ["b"]=>
  string(10) "Sumanadasa"
  ["c"]=>
  string(6) "Lakmal"
  ["d"]=>
  string(11) "Nanayakkara"
}

again :D

in the received page you can use:

parse_str($str, $array); var_dump($array);

You can combine urlencoded with json_encode

Exemple:

<?php

$cars = array
(
    [0] => array
        (
            [color] => "red",
            [name] => "mustang",
            [years] => 1969
        ),

    [1] => array
        (
            [color] => "gray",
            [name] => "audi TT",
            [years] => 1998
        )

)

echo "<img src='your_api_url.php?cars=" . urlencode(json_encode($cars)) . "'/>"

?>

Good luck !

Very easy to send an array as a parameter.

User serialize function as explained below

$url = www.example.com

$array = array("a" => 1, "b" => 2, "c" => 3);

To send array as a parameter

$url?array=urlencode(serialize($array));

To get parameter in the function or other side use unserialize

$param = unserialize(urldecode($_GET['array']));

echo '<pre>';
print_r($param);
echo '</pre>';

Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)
Related