Is it possible to have a value in $_GET
as an array?
If I am trying to send a link with http://link/foo.php?id=1&id=2&id=3
, and I want to use $_GET['id']
on the php side, how can that value be an array? Because right now echo $_GET['id']
is returning 3
. Its the last id which is in the header link. Any suggestions?
This question is related to
php
You can specify an array in your HTML this way:
<input type="hidden" name="id[]" value="1"/>
<input type="hidden" name="id[]" value="2"/>
<input type="hidden" name="id[]" value="3"/>
This will result in this $_GET array in PHP:
array(
'id' => array(
0 => 1,
1 => 2,
2 => 3
)
)
Of course, you can use any sort of HTML input, here. The important thing is that all inputs whose values you want in the 'id' array have the name id[]
.
You can get them using the Query String:
$idArray = explode('&',$_SERVER["QUERY_STRING"]);
This will give you:
$idArray[0] = "id=1";
$idArray[1] = "id=2";
$idArray[2] = "id=3";
Then
foreach ($idArray as $index => $avPair)
{
list($ignore, $value) = explode("=", $avPair);
$id[$index] = $value;
}
This will give you
$id[0] = "1";
$id[1] = "2";
$id[2] = "3";
You could make id
a series of comma-seperated values, like this:
index.php?id=1,2,3&name=john
Then, within your PHP code, explode it into an array:
$values = explode(",", $_GET["id"]);
print count($values) . " values passed.";
This will maintain brevity. The other (more commonly used with $_POST) method is to use array-style square-brackets:
index.php?id[]=1&id[]=2&id[]=3&name=john
But that clearly would be much more verbose.
When you don't want to change the link (e.g. foo.php?id=1&id=2&id=3
) you could probably do something like this (although there might be a better way...):
$id_arr = array();
foreach (explode("&", $_SERVER['QUERY_STRING']) as $tmp_arr_param) {
$split_param = explode("=", $tmp_arr_param);
if ($split_param[0] == "id") {
$id_arr[] = urldecode($split_param[1]);
}
}
print_r($id_arr);
Yes, here's a code example with some explanation in comments:
<?php
// Fill up array with names
$sql=mysql_query("SELECT * FROM fb_registration");
while($res=mysql_fetch_array($sql))
{
$a[]=$res['username'];
//$a[]=$res['password'];
}
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
?>
Put all the ids into a variable called $ids and separate them with a ",":
$ids = "1,2,3,4,5,6";
Pass them like so:
$url = "?ids={$ids}";
Process them:
$ids = explode(",", $_GET['ids']);
I think i know what you mean, if you want to send an array through a URL you can use serialize
for example:
$foo = array(1,2,3);
$serialized_array = serialize($foo);
$url = "http://www.foo.whatever/page.php?vars=".urlencode($serialized_array);
and on page.php
$vars = unserialize($_GET['vars']);
Source: Stackoverflow.com