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.
}
Related
I need to get values of array through a loop with dynamic vars.
I can't understand why the "echo" doesn’t display any result for "$TAB['b']".
Do you know why ?
The test with error message : https://3v4l.org/Fp3GT
$TAB_a = "aaaaa";
$TAB['b'] = "bbbbb";
$TAB['b']['c'] = "ccccc";
$TAB_paths = ["_a", "['b']", "['b']['c']"];
foreach ($TAB_paths as $key => $value) {
echo "\n\n\${'TAB'.$value} : "; print_r(${'TAB'.$value});
}
You are treating the array access characters as if they are part of the variable name. They are not.
So if you have an array $TAB = array('b' => 'something');, the variable name is $TAB. When you do ${'TAB'.$value}, you're looking for a variable that's actually named $TAB['b'], which you don't have.
Since you say that you just want to be able to access array indexes dynamically based on the values in another array, you just put the indexes alone (without the array access characters) in the other array.
$TAB['b'] = 'bbbbbb';
$TAB['c'] = 'cccccc';
$TAB_paths = array('b', 'c');
foreach ($TAB_paths as $key => $value) {
echo "\n\n".'$TAB['."'$value'".'] : ' . $TAB[$value];
}
Output:
$TAB['b'] : bbbbbb
$TAB['c'] : cccccc
DEMO
It's unclear what you're trying to do, although you need to include $TAB_all in $TAB_paths:
$TAB_paths = [$TAB_all['a'], $TAB_all['aside']['nav']];
Result:
${TAB_all.aaaaa} : ${TAB_all.bbbbb} :
Not certain what you're needing. My guess you need to merge two arrays into one. Easiest solution is to use the array_merge function.
$TAB_paths = array_merge($TAB_a1, $TAB_a2);
You can define the variable first
foreach ($TAB_all as $key => $value) {
${"TAB_all" . $key} = $value;
}
Now Explore the result:
foreach ($TAB_all as $key => $value) {
print_r(${"TAB_all" . $key});
}
I am having an php session array like
["cart"]["123"] = "Biscuit"
["cart"]["124"] = "Jam"
If I want to access the 2nd element I will access array_values($_SESSION["cart"])[$i]
where $i runs in for loop. If I want to get the values "123" and "124", how can i achieve it in a for loop with only "cart" and $i..?
foreach($_SESSION['cart'] as $key => $value)
{
echo $key; // your 123 or 124 key
}
This is an associative array easiest and best way is foreach because have to deal with key-value pairs rather than indexes(numbers).
foreach($arr['cart'] as $key => $val){
echo "$key<br/>";
}
I used a variable to hold values($arr)
But you can try for loop also:
$keys = array_keys($arr['cart']);
for ($keyindex = 0; $keyindex < count($keys); $keyindex++) {
$key = $keys[$keyindex];
echo $key."<br>";
}
I need to work with a hashtable which values can store variables like:
$numberOfItems
$ItemsNames
If I ain't wrong, that would mean another hash like array as value.
What should be the right syntax for inserting and iterating over it?
Is anything like:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
valid?
if there's no chance to have collusion in item name, you can use the name in key
$hash[$ItemsName] = $numberOfItems;
in the other case, use an integer for example as a key, then the different "attributes" you want as keys for the 2nd array
$hash[$integer]["count"] = $numberOfItems;
$hash[$integer]["name"] = $name;$
Then, for iterating (1st case):
foreach ($hash as $name => $number) {
echo $number;
echo $name;
}
or, 2nd case
foreach ($hash as $item) {
echo $item["name"];
echo $item["count"];
}
To create php array, which can be a hash table, you can do:
$arr['element'] = $item;
$arr['element'][] = $item;
$arr['element'][]['element'] = $item;
Other way:
$arr = array('element' => array('element' => array(1)));
To iterate over it use foreach loop:
foreach ($items as $item) {
}
It's also possible to create nested loops.
About your case:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
I would do:
$hash['anyKey']['numberOfItems'] = 15;
$hash['anyKey']['ItemsNames'] = array('f','fw');
I have dynamic field names that are being posted to my form processor. The names are formatted like editnote|9. |9 being the ID of the note to edit. If I use this code:
foreach($_POST as $key) {
$editcheck = explode('|', $key);
if($editcheck[0] == 'editnote') {
echo $editcheck[1];
}
}
I can properly get the ID of 9, but I cannot get the value. I have tried:
foreach($_POST as $key => $value) {
$editcheck = explode('|', $key);
if($editcheck[0] == 'editnote') {
$clsCNA->updatenote($editcheck[1], $_POST[$key]);
}
}
But with this code, I can only get the value and not the key name to get the note ID I want to edit.
So basically, I want foreach($_POST as $key => $value) to somehow allow me to get the name of $key so I can explode it to get the ID number.
Any ideas?
I am trying to send to my class like this:
$clsCNA->updatenote(ID From key name, Value of key)
If I use this code:
foreach($_POST as $key) {
$editcheck = explode('|', $key);
if($editcheck[0] == 'editnote') {
echo $editcheck[1];
}
}
I can properly get the ID of 9...
foreach($_POST as $key => $value) {
CUT ...
As PHP's foreach loop using one variable will only take the values of the array. The exact names chosen does not determine what what goes into the variables. Similarly found by method calls.
This will be put the Value into the $key variable.
In the second example you are using the $key => $value syntax. Here the loop puts the Key into the $key variable and the Value into the $value variable.
What this means is that your $key variable is not the same in both examples. In one it holds the Values of the array in the other it holds the Keys.
I am trying to figure out how I can handle possible duplicate array keys.
I have this form with a select dropdown which can select multiple options (more than 1). And I am using jQuery.serialize() to serialize the form on submit.
The serialized string for a multi-select element would look like so:
select=1&select=2&select=3 // assumming I selected first 3 options.
Now in the PHP side, I have the following code to handle the "saving" part into a database.
$form_data = $_POST['form_items'];
$form_data = str_replace('&','####',$form_data);
$form_data = urldecode($form_data);
$arr = array();
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
$arr[$key] = $value;
}
Ok this all works for the rest of the form elements but when it comes to the select element, it only picks the last selected key/value pair. So my array now looks like this:
Array ( [select_element] => 3)
What I need, is for it to look like:
Array ( [select_element] => '1,2,3')
So I guess what I am asking is based on my code, how can I check if a key already exists and if it does, append to the $value.
If you can modify the client-side code, I would rather change the name of the select to select[], that way it will be parsed as an array in your server script.
You can't have multiple keys with the same name... They're unique keys. What it's doing is setting select = 1, then select = 2, then select = 3 and you end up with your final value of 3.
If you want to allow multiple choices in your select menu, you should change the name of the element so that it submits that data as an array, rather than multiple strings:
<select name="select[]" multiple="multiple">
which should result in something like this instead:
select[]=1&select[]=2&select[]=3
and when PHP requests that data, it will already be an array:
$data = $_POST['select'];
echo print_r($data); // Array(1, 2, 3)
PHP has its own way of encoding arrays into application/x-www-form-urlencoded strings.
PHP's deserialization of x-www-form-urlencoded is implemented by parse_str(). You can think of PHP as running these lines at the beginning of every request to populate $_GET and $_POST:
parse_str($_SERVER['QUERY_STRING'], $_GET);
parse_str(file_get_contents('php://input'), $_POST);
parse_str() creates arrays from the query string using a square-bracket syntax similar to its array syntax:
select[]=1&select[]=2&select[]=3&select[key]=value
This will be deserialized to:
array('1', '2', '3', 'key'=>'value');
Absent those square brackets, PHP will use the last value for a given key. See this question in the PHP and HTML FAQ.
If you can't control the POSTed interface (e.g., you're not able to add square-brackets to the form), you can parse the POST input yourself from php://input and either rewrite or ignore the $_POST variable.
(Note, however, that there is no workaround for multipart/form-data input, because php://input is not available in those cases. The select=1 and select=2 will be completely and irretrievably lost.)
Ok, I was able to resolve this issue by using the following code:
if (array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key].','.$value;
} else {
$arr[$key] = $value;
}
So now the loop looks like this:
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
if (array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key].','.$value;
} else {
$arr[$key] = $value;
}
}
This will essentially string up the value together separated by a comma which can then be exploded out into an array later.
You should change your client-side code to send the augmented value: array.join(","); and use that in your PHP side. Because when your data reaches your script, the other values have already been lost.
This should give you the solution you require
$form_data = str_replace('&','####',$form_data);
$form_data = urldecode($form_data);
$arr = array();
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
if (isset($arr[ $key ])) {
$arr[$key] = ','.$value;
} else {
$arr[$key] = $value;
}
}