Get names of GET method variables - php

I have about 5 variables in GET method. They almost always have different names, encoded mostly. How i can get name (not value) of those variables.
example:
$_GET['orchid'] = red;
$_GET['xyc'] = wrack;
and after that, next time i open the page:
$_GET['rose'] = red;
$_GET['gzuy'] = bottle;
Values are not important for now, in this case I need names of variables: "orchid", "xyc" or in second case "rose" and "gzuy".

array_keys($_GET)
For more informations, see the link bellow:
http://php.net/manual/function.array-keys.php

foreach ($_GET as $key=>$value){
echo $key;
}

array_keys() should do the trick:
$keys = array_keys($_GET);

foreach ($_GET as $key => $value) {
//Line below is optional to get around empty values.
if (!empty($value))
echo $key, ' ';
}
The above code will print out all of the set $_GET variables, having file.php?moo will mark moo as set but with a value of nothing. The below snippet will simply return an array just containing the names of the $_GET variables which can then be used in $_GET[$keys[0]] for example to recall its value.
array_keys($_GET);
Docs:
foreach loop
array_keys()

Related

foreach $key variable clarification

I have this code
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key) {
$input = implode(",", $key);
}
} /*end is isset $_POST['submit2'] */
echo $input;
it produces the error " implode(): Invalid arguments passed " when I change the implode arguments to implode(",", $_POST['check_list']) it works as intended.
Can someone clarify why? As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?
Sorry if it's a silly question, I'm self taught and sometimes details like that are hard to find online.
You seem confused at several levels, so let me clarify some of them:
You said 'As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?'. The answers are NO and NO:
The $key variable outside the foreach loop will contain the last element of the array that's stored in $_POST['check_list'], $_POST['submit2'] seems to be only used to check if is set and nothing else in your piece of code. What foreach does is to traverse any iterator variable (an array in your case) and set the current item in a variable ($key) in your case. So after the loop, $key will contain the last element of that array. For more information refer to the docs: [http://php.net/manual/en/control-structures.foreach.php]
implode expects the second parameter to be an array, it seems you're not providing an array, but any other type. Is the last item of $_POST['check_list'] actually an array?
If you're trying to 'glue' together all items of $_POST['check_list'], you don't need to iterate, you just use implode on that one: $input = implode(",", $_POST['check_list']);. Otherwise, i'm not sure what are you trying to do.
Maybe if you explain what are you trying to do, we can help better.
Foreach already iterates trough your values. You can either get the value and echo it from there or you can add it to another array input if thats what you need:
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key => $value) {
$input[] = 'Value #'. $key .' is ' . $value;
}
}
echo implode(",", $input);
You are saying that $_POST['check_list'] is an array if implode() works on it, so no need to loop to get individual items. To implode() the values:
echo implode(',', $_POST['check_list']);
To implode() the keys:
echo implode(',', array_keys($_POST['check_list']));
foreach() iterates over an array to expose each item and get the individual values and optionally keys one at a time:
foreach($_POST['check_list'] as $key => $val) {
echo "$key = $value<br />";
}
implode function needs array as second argument. You are passing string value as second argument. That's why it's not working.

PHP Get input name

Upon posting a form using _GET I would like to get the input name
See below part of url upon submit
.php?14=0&15=0&16=0&17=0&18=0&19=0
I know how to get the variable E.G:
$14=$_GET["14"];
Which is 0
However is it possible to do this and get the input name (eg 14) and then turn these into variables? (To save the input name to the DB)
To get all the $_GET parameters, you can do:
foreach($_GET as $key => $value){
echo "Key is $key and value is $value<br>";
}
This will output each key (14, 15, 16 etc) and value (0, 0, 0 etc).
To bind a variable name with a variable string, look at variable variables:
foreach($_GET as $key => $value){
$$key = $value;
}
As a result, you will have the following variables with the following values:
$14 = 0;
$15 = 0;
$16 = 0;
// etc...
Alternatively (as you don't necessarily know what the key/value pairs would be), you could create an empty array and add these keys and values to it:
foreach($_GET as $k => $v){
$arr[$k] = $v;
}
The resulting array will be:
$arr[14] = 0;
$arr[15] = 0;
$arr[16] = 0;
// etc...
Solution using single loop (Update):
If you're just using question/answer single time you can do it in single loop like this,
<?php
foreach($_GET as $key => $value){
$question = $key;
$answer = $value;
// Save question and answer accordingly.
}
If you will be using question answer to perform other things, use the following method.
You can get all the keys using array_keys(), where $_GET is an array.
Use it like this,
<?php
$keys=array_keys($_GET);
print_r($keys); // this will print all the keys
foreach($keys as $key) {
// access each key here with $key
}
Update:
You can make a pair of question,answer array and put it in the main array to insert it in the database like this,
<?php
$mainArray=array();
$keys=array_keys($_GET);
foreach($keys as $key) {
// access each key here with $key
$questionAnswerArray=array();
$questionAnswerArray["question"]=$key;
$questionAnswerArray["answer"]=$_GET[$key];
$mainArray[]=$questionAnswerArray;
}
// Now traverse this array to insert the data in database.
foreach($mainArray as $questionanswer) {
echo $questionanswer["question"]; //prints the question
echo $questionanswer["answer"]; // prints the answer.
}

Assign GET variable to another in PHP when you know part of the name of the GET variable

I have some problems with GET variable in PHP.
I need to assign a GET variable to a normal variable in PHP, but the name of the GET variable is not always the same name.
Ex. $telf=$_GET['t_1'].
But can be $_GET['t_6'], $_GET['t_18'].
There's any way to assign all possible names of $_GET['t_XX'] to another variable?
You could use preg_grep.
With preg_grep you can get all keys in $_GET that start with 't_'. Then you walk over these values, and print (or do whatever you want) with the key + value.
Please see this example:
$keys = preg_grep("/^t_.*/", array_keys($_GET));
foreach($keys as $key) {
echo $key.' holds value '.$_GET[$key].PHP_EOL;
}
Another option a bit lighter in resources is using strpos on the keys
foreach ( $_GET as $keys => $values ) {
if ( strpos( $keys, 't_' ) !== false ) {
$final_var = $values;
}
}

Read only parameter name in Querystring with $_GET

How can I read only the parameter name from a querystring in PHP? For example in both of these:
www.example.com/index.php?a='1'
www.example.com/index.php?a
the wanted output is:
a
You can use the array_keys of the global $_GET array:
$keys = array_keys($_GET);
echo $keys[0]; // echos a
You need get a key of a GET:
foreach ($_GET as $key => $val)
{
print($key);
}
Or a get via print_r(array_keys($_GET)); function.
$_GET is just an array variable (not command). It is populated with parameter names as keys in this array, and parameter values as the corresponding values.
So just use array_keys($_GET).

using a foreach loop to initialize variables

I have built an empty associative array whos keynames refer to submitted post data. I can capture the postdata just fine, but I run into trouble trying to instantiate variables who's names match the array key.
for example:
$insArray = array('rUsername'=>'', 'rPass'=>'', 'rQuestion'=>'', 'rAnswer'=>'', 'rFName'=>'', 'rLName'=>'', 'rBDateD'=>'', 'rBDateM'=>'', 'rBDateY'=>'', 'rHCheck'=>'', 'rHCeckOption'=>'', 'rEmail'=>'');
foreach($insArray as $key=>$value){
if (filter_input(INPUT_POST, $key) != ''){
$key = stripslashes(filter_input(INPUT_POST, $key));
$insArray[$key] = $key;
}
}
First line creates the empty array, then the foreach loops through this array. Now it gets tricky.
filter_input(INPUT_POST, $key) captures the value located in the post data matching the current key, rUsername in this case
$key is where the problem lies. I want the NAME of the new variable to be the associative key name, for example I want to replace $key with $rUsername in the first iteration, $rPass in the second, and so on. I tried using two $$, but I know that's not right. Never tried doing this before, but it would be helpful if I could figure it out.
UPDATE:
This is the final code which was a combination of two of the answers provided.
if (isset($_POST['submit'])) {
//Build array of variables to be put into database
$insArray = array('rUsername'=>'', 'rPassword'=>'', 'rQuestion'=>'', 'rAnswer'=>'', 'rFName'=>'', 'rLName'=>'', 'rBDateD'=>'', 'rBDateM'=>'', 'rBDateY'=>'', 'rHCheck'=>'', 'rHCheckOption'=>'', 'rEmail'=>'');
foreach(array_keys($insArray) as $key){
$insArray[$key] = filter_input(INPUT_POST, $key);
$$key = filter_input(INPUT_POST, $key);
}
}
Gave me exactly the output I wanted, thanks guys!
You're not accessing $_POST at all, so all you're doing is taking some array members you defined yourself, filtering them for harmful POST characters (why would you attempt to inject your own code?) and then creating a new array from those self-defined key values.
If I'm guessing right at what you want, it should be this:
foreach(array_keys($insArray) as $key) {
$insArray[$key] = stripslashes(filter_input(INPUT_POST, $_POST[$key]));
}
The use of stripslashes suggests that you're on a braindead version of PHP which has magic_quotes enable. You should upgrade to a modern version of PHP and/or turn them off.
The solution is change
$key = stripslashes(filter_input(INPUT_POST, $key));
to
$$key = stripslashes(filter_input(INPUT_POST, $key));
See http://www.php.net/manual/en/language.variables.variable.php
Also, recheck your code, which are doing some mistakes..
If I understand you correctly, Im going to suggest this approach:
$defaultValues = array('rUsername'=>'', 'rPass'=>'', 'rQuestion'=>'', 'rAnswer'=>'', 'rFName'=>'', 'rLName'=>'', 'rBDateD'=>'', 'rBDateM'=>'', 'rBDateY'=>'', 'rHCheck'=>'', 'rHCeckOption'=>'', 'rEmail'=>'');
$values = array_map('stripslashes', array_merge($defaultValues, array_filter($_POST)));
extract($values, EXTR_SKIP);
echo $rUsername;
echo $rPass;
.........
By using the snippet above, you have to take into account the following
Im using the extract function with EXTR_SKIP so you dont overwrite existing variables. Make sure to only use the variables you need in your code and sanitize them appropietly.
By using array_filter on the $_POST superglobal im "erasing" all empty or null variables. so if an expected key was not sent via $_POST, it defaults to the value specified by the $defaultValues array.
I dont quite understand why you are using filter_input without the third parameter (filter constants).
Hope this will help, If not may be I have misunderstood the problem.
Instead of
$key = stripslashes(filter_input(INPUT_POST, $key));
$insArray[$key] = $key;
Try
$insArray[$key] =stripslashes(filter_input(INPUT_POST, $key));
Then after the foreach loop
extract($insArray);

Categories