I am trying to pass an array of values through a form submission. As an example:
example.com?value1=178&value2=345&value3=2356
The easy solution would be for me to do the following to get the values on the new page:
$value1=$_GET['value1'];
$value2=$_GET['value2'];
$value3=$_GET['value3'];
The difficulty that I am having is that the variable after the word 'value' passed through the form will change with each submission. So I have amended the code to pass as:
example.com?value14=178&variable=14&value23=345&variable=23&value63=2356&variable=63
As you can see here, I have now passed the variable that comes in from of the value as a GET parameter. My attempt then GET these values to display individually on the submitted page is as follows:
$variable=$_GET['variable'];
$value=$_GET['value'.$variable];
echo $value . '<br>';
This code almost works. I am able to get the last array which is passed through to display. How can I fix this code to get all of the passed values to display on the submitted page?
Use PHP's array notation for form fields:
val[]=178&val[]=14&val[]=345&etc...
This will cause $_GET['val'] to be an array:
$_GET = array(
'val' => array(178, 14, 345, etc...)
)
If you can't rearrange the URL like that, you can try using preg_grep:
$matches = preg_grep('/^variable\d+$/', array_keys($_GET));
which'll return :
$matches= array('variable1', 'variable2', 'variable3', etc...);
Use an array, for example like this without the need for variable $variable.
example.com?value[14]=178&value[23]=345&value[63]=2356
foreach ($_GET['value'] as $key => value) {
echo $key . " => " . $value . "<br/>";
}
EDIT: Another way for getting the values would be looping the whole $_GET -array and parsing values from there like this (variables are always in the form of "value" followed by X numbers):
example.com?value14=178&value23=345&value63=2356
$values = array();
foreach ($_GET as $key => $value) {
if (preg_match('/^value[\d]+$/', $key)) {
// remove "value" from the beginning of the key
$key = str_replace('value', '', $key);
// save result to array
$values[$key] = $value;
}
}
See http_build_query()
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});
}
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.
}
All,
I have a form that has some text inputs, checkboxes, select box and a textarea. I want to submit the form with PHP using a submit button to a page for processing.
That part is fine but what I would like to do is basically get the results into an array so I can do a foreach loop to process the results.
Basically I'm trying to create a dynamic form the submits to my backend processing script and don't want to hard code in the post values like the following:
$var1 = $_POST['var1'];
echo $var1;
$var2 = $_POST['var2'];
echo $var2;
Does anyone know how to go about doing something like this or give any recommendations?
If there're no other data in your POST but these generated elements, just do
foreach( $_POST as $key => $val ) {
// do your job
}
and process what you have. If you want to mix your generated entries with predefined you may want to put these generated in nested array:
<input ... name="generated[fieldname]" />
and then you iterate
foreach( $_POST['generated'] as $key => $val ) {
// do your job
}
Just use array notation:
<input name="vars[]" value="" />
Then you will have something like this as $_POST:
Array ('vars' => Array(
0 => 'val1'
1 => 'val2'
)
)
foreach ($_POST as $param_name => $param_val) {
echo "Param: $param_name; Value: $param_val";
}
Actually, the $_POST variable is an array. you just need to extract the array values by using a simple foreach loop. that's it.
I hope this example help you.
foreach($_POST as $field_name => $val)
{
$asig = "\$".$field_name."='".addslashes($val)."';";
eval($asig);
}
After running this script all the POST values will be put in a variable with the same name than the field's name.
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;
}
}
I want to save the name of all the $_GET variables in a url, but im not sure where to start, or finish for that matter.
For example:
if i have:
url: test.com/forums.php?topic=blog&discussion_id=12
can i use php to get the name, i.e. "topic" and "discussion_id from the $_GET variables and can i then store the values: "topic" and "discussion_id" in an array?
You can get this by calling array_keys on $_GET:
$getVars = array_keys($_GET);
If this isn't about the current URL, but just some $url string you want to extract the parameters from then:
parse_str(parse_url($url, PHP_URL_QUERY), $params);
will populate $params with:
[topic] => blog
[discussion_id] => 12
Use the following code to grab data from the URL using GET. Change it to $_POST will work for post.
<?php
foreach ( $_GET as $key => $value )
{
//other code go here
echo 'Index : ' . $key . ' & Value : ' . $value;
echo '<br/>';
}
?>
$_GET is usual php-array. you may use it in foreach loop:
foreach ($_GET as $k => $v)
echo ($k . '=' . $v);
It's an array:
print_r($_GET);
Fetch the elements as you would with any other array.