How to get PHP $_GET array? - php

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?

The usual way to do this in PHP is to put id[] in your URL instead of just id:
http://link/foo.php?id[]=1&id[]=2&id[]=3
Then $_GET['id'] will be an array of those values. It's not especially pretty, but it works out of the box.

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.

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

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

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

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

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];
}
}
}
}
?>

Related

Get array value based on variable and indexes as string

I'm trying to execute variable which part of it is a string.
Here it is:
$row = array(
'index_1' => array(
'index_2' => 'my-value'
)
);
$pattern = "['index_1']['index_2']";
I tried to do it in following ways:
// #1
$myValue = $row{$pattern};
// #2
$myValue = eval("$row$pattern");
I also trying to get it working with variable variable, but not successful.
Any tips, how should I did it? Or myabe there is other way. I don't know how may look array, but I have only name of key indexes (provided by user), this is: index_1, index_2
You could use eval but that would be quite risky since you say the values come from user input. In that case, the best way might be to parse the string and extract the keys. Something like this should work:
$pattern = "['index_1']['index_2']";
preg_match('/\[\'(.*)\'\]\[\'(.*)\'\]/', $pattern, $matches);
if (count($matches) === 3) {
$v = $row[$matches[1]][$matches[2]];
var_dump($v);
} else {
echo 'Not found';
}
This can help -
$row = array(
'index_1' => array(
'index_2' => 'my-value'
)
);
$pattern = "['index_1']['index_2']";
$pattern = explode("']['", $pattern); // extract the keys
foreach($pattern as $key) {
$key = str_replace(array("['", "']"), '', $key); // remove []s
if (isset($row[$key])) { // check if exists
$row = $row[$key]; // store the value
}
}
var_dump($row);
Storing the $row in temporary variable required if used further.
Output
string(8) "my-value"
If you always receive two indexes then the solution is quite straight forward,
$index_1 = 'index_1';// set user input for index 1 here
$index_2 = 'index_2';// set user input for index 2 here
if (isset($row[$index_1][$index_2])) {
$myValue = $row[$index_1][$index_2];
} else {
// you can handle indexes that don't exist here....
}
If the submitted indexes aren't always a pair then it will be possible but I will need to update my answer.
As eval is not safe, only when you know what you are ding.
$myValue = eval("$row$pattern"); will assign the value you want to $myValue, you can add use return to make eval return the value you want.
here is the code that use eval, use it in caution.
demo here.
<?php
$row = array(
'index_1' => array(
'index_2' => 'my-value'
)
);
$pattern = 'return $row[\'index_1\'][\'index_2\'];';
$myValue = eval($pattern);
echo $myValue;

How to use variable inside the parameter of $_POST in php

I will be getting some certain amount of data. I will get the number for which the for loop to be run.
For example
I get the number 3 and I will get three parameters like par1,par2 and par3 then how should I pass this par1 in the $_post
like
$i=$_POST["number"];
for($i=1;$i<=$n;$i++)
{
$par.$i = $_POST["par".$i];
}
Here I cant get the value from $_POST["par".$i];
As it is not able to get the variable inside the paramater of $_POST
Any help will be thankful
I suggest that you create a new array $par and there you will put by index all the par you will have like this:
$i=$_POST["number"];
$par = [];
for($i=1;$i<=$n;$i++)
{
$par[$i] = $_POST["par".$i];
}
After that if you want to go throw all pars you can simply use foreach like this:
foreach($par as $key => $value) {
// $key will be 1,2,3
// $value will be the value from $_POST["par" . $i]
}
The . is to concatenate two strings in PHP, and you can't create a new variable like you tried. If you want to have in $par1, $par2 and $par3 you can do like this:
${"par" . $i} = $_POST["par".$i];
But I don't recommend this way because it's more hard to handle.
One Way
According to your question.
<?php
$n = $_POST["number"];
$par = "par";
for($i=1; $i<=$n; $i++){
$par.$i = $_POST["par".$i];
}?>
Alternative Way
In this scenario,
For example I get the number 3 and I will get three parameters like
par1,par2 and par3 then how should I pass this par1 in the $_post.
Better, make 'par' input name as an array type as 'par[]' (<input type='text' name='par[]'>) in your file instead using par1, par2 .. par(n).
And, no need to worry in submit page.
<?php
$n = $_POST["number"];
for($i=1;$i<= $n;$i++){
$newPar = $_POST["par"][$i];
// Write here your logic to use how you want.
}
?>

how to store values from form and store it in an array

I have tried :
<?php
$array = array();
for ($i=0;$i <20;$i++)
{
$comm = mysql_escape_string($_POST['comments']);
array_push($array,$comm);
echo $comm;
}
?>
but i am getting only 1 value.
i want to show all the values in the array
Rizier123 answer is 100% correct, but just for your understanding you can use something like this too:
<?php
$array = array();
foreach ($_POST as $comm)
{
$comm = mysql_escape_string($comm);
array_push($array,$comm);
echo $comm;
}
?>
Because you only go through this post variable: $_POST['comments'].
Make it simple and do something like this:
(Here I get all values with array_values() from the $_POST variable then I go through each element with array_map() and call mysql_escape_string() on them)
$array = array_map("mysql_escape_string", array_values($_POST));

$_POST metacharacters?

in my $_POST, I have a variable whose name changes. the name is modify_0, but the number at the end changes depending on the button that was pressed.
Is there anyway to check what the number is for that variable in $_POST?
Say:
$_POST['modify_(check for number or any character)']
You would need to iterate over all of the keys within the $_POST variable and take a look at their format:
$post_keys = array_keys( $_POST );
foreach($post_keys as $key){
if ( strpos($key, 'modify_' ) != -1 ){
// here you know that $key contains the word modify
}
}
Besides the correct answers given above, I would recommend changing your code slightly so it's easier to work with.
Instead of having inputs with the format:
// works for all types of input
<input type="..." name="modify_1" />
<input type="..." name="modify_2" />
You should try:
<input type="..." name="modify[1]" />
<input type="..." name="modify[2]" />
This way, you can iterate through your data in the following way:
$modify = $_POST['modify'];
foreach ($modify as $key => $value) {
echo $key . " => " . $value . PHP_EOL;
}
This works especially well for multiselects and checkboxes.
Try something like this:
// First we need to see if there are any keys with names that start with
// "modify_". Note: if you have multiple values called "modify_X", this
// will take out the last one.
foreach ($_POST as $key => $value) {
if (substr($key, 0) == 'modify_') {
$action = $key;
}
}
// Proceed to do whatever you need with $action.

Get the ids and loop through post data

I post a form with the same input names+id at the end like that:
<input type="text" name="machine_1">
<input type="text" name="machine_11">
<input type="text" name="machine_23">
How loop through on each of them and get the id's in the loop?
I tried this way, but it will loop a lot without any data and what happens if there is more thank 100 id?
for($i=0; $i<100; $i++){
$_POST["machine"]=$_POST["machine_".$i];
$id=$i;
}
POST is an associate array, so you can loop through everything that's been posted like this:
//$k contains the id
//$v contains the submitted value
foreach($_POST as $k => $v) {
//test if id contains 'machine'
if(stristr($k, 'machine')) {
echo $v;
}
}
You can do this using a foreach loop, like so:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value';
}
$_POST["machine"]=$_POST["machine_".$i];
here $_POST['machine'] represents noting..how can you assign a value to $_POST['machine']..you havent passed any element having name machine while submitting the form..so first of all you need to check it bro
In your code, you have:
$_POST["machine"]=$_POST["machine_".$i];
That's not the correct way. You want to store the value of $_POST["machine_".$i] to $id and then use it below.
This is probably what you need:
for($i=1; $i<100; $i++){
$id = $_POST["machine_".$i];
echo $id;
}
And if there are more than 100 elements, and you don't know the number of inputs, then you can use a foreach loop, as below:
$i = 1; // counter variable
foreach ($_POST as $key => $input) {
if($key == "machine_".$i) {
$id = $input; // or simply 'echo $input'
echo $id;
}
$i++; // increment counter
}

Categories