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.
}
?>
Related
I want to get keys and values from a multi-dimensional array dynamically, to better explain what I'm trying to achieve please see the code below.
$i = 0;
foreach ($faq as $f) {
$q = 'faq'.$i;
$a = 'faq'.$i.'_answer';
echo $faq['faq1'][$i];
echo $faq['faq1_answer'][$i];
$i++;
}
The literal text above faq1 and faq1_answer needs to be replaced by the variable $q and $a respectively for me to be able to get the keys and values dynamically, but I cannot figure out how to add the variable.
The keys will always be the same, except for the number, which will change from 1 to 99. So with the code above, I can get the value of faq1 but I also need to grab the value of faq2 etc, hence why the variables above would work as I need.
tl;dr faq1 needs to be able to change to faq2 on the next iteration, hence the reason for me using $i.
Maybe like this?
$i = 0;
foreach ($faq as $f) {
$q = 'faq'.$i;
$a = 'faq'.$i.'_answer';
echo $f[$a];
echo $f[$a];
$i++;
}
I know the title is not describing the problem very well, so I explain here:
I have multiple $_POST with similar names, like question1,question2,question3...
I have a for loop with $i. i want to get this vars ($question1, $question2), in help with $i. For example:
$question.$i = $_POST['question' . $i];
I want to do it because the number of questions is variable, so I have a button that add questions and answers to the page and then you submit it.
First, you need to make explicitly $question an array.
Then you build your $_POST index by concatenating the string and $i with a ..
So, before the loop:
$question = array();
and in the loop:
$question[$i] = $_POST['question'.$i];
If you don't want an array in your loop, this should fit:
${'question' . $i} = $_POST['question'.$i];
When $i=1, this will get you a $question1 variable filled with then content of $_POST['question1'].
See also Dynamic variable names in PHP which adds insight on the problem.
$question = array();
$question[] = $_POST['question'.$i];
Use array to get your values.
I am attempting to use a for loop or for each loop to push the values from a get query to another variable. May I have some help with this approach?
Ok here is where I am:
for ($i = 0 ; i < $_GET['delete']; i++) {
$_jid [] = $_GET['delete'];
}
You don't actually need a loop here. If $_jid already is an array containing some values, consider just merging it with $_GET['delete'].
if (is_array($_jid)) {
$_jid = array_merge($_jid, $_GET['delete']);
}
If $_jid is not an array and doesn't exist except as a container for $_GET['delete'] you do can just assign the array. There is no need to loop at all.
$_jid = $_GET['delete'];
Of course in that case, you don't even need to copy it. You can just use $_GET['delete'] directly, in any context you planned to read from $_jid.
Update:
If the contents of $_GET['delete'] are originally 923,936, that is not an array to begin with, but rather a string. If you want an array out of it, you need to explode() it on assignment:
$_jid = explode(',', $_GET['delete']);
But if you intend to implode() it in the end anyway, there's obviously no need to do that. You already have exactly the comma-delimited string you want.
As you can see if you do a var_dump($_GET), the variable $_GET is a hashmap.
You can easily use a foreach loop to look through every member of it :
foreach($_GET as $get) // $get will successively take the values of $_GET
{
echo $get."<br />\n"; // We print these values
}
The code above will print the value of the $_GET members (you can try it with a blank page and dull $_GET values, as "http://yoursite.usa/?get1=stuff&get2=morestuff")
Instead of a echo, you can put the $_GET values into an array (or other variables) :
$array = array(); // Creating an empty array
$i = 0; // Counter
foreach($_GET as $get)
{
$array[$i] = $get; // Each $_GET value is store in a $array slot
$i++;
}
In PHP, foreach is quite useful and very easy to use.
However, you can't use a for for $_GET because it's a hashmap, not an array (in fact, you can, but it's much more complicated).
Hope I helped
I have a code like that:
session_start();
$user = $_GET['user'];
$mode = $_GET['mode'];
$id1 = $_GET['id1'];
$id2 = $_GET['id2'];
$id3 = $_GET['id3'];
$id4 = $_GET['id4'];
$id5 = $_GET['id5'];
$id6 = $_GET['id6'];
$id7 = $_GET['id7'];
$id8 = $_GET['id8'];
$dep= $mode;
switch ($dep)
{
case "3m":
$dep = "Text 1";
break;
case "all":
$dep = "More text";
break;
default:
$dep = "Text1";
}
There are more other cases. I think I will have more id's and cases soon. Is there a simpler way to get all id's from URL push them into PHP code for evaluating?
I have found a code foreach:
foreach($_GET as $key => $value) {
echo 'key is: <b>' . $key . '</b>, value is: <b>' .$value. '</b><br />';
}
And it gets all variables from URL, but how to change the code in order to have it like this:
$variable = $_GET['variable'];
Any help appreciated :)
Use arrays, that's exactly what they're for. Name the parameters in the URL like:
id[]=1&id[]=2&...
Then $_GET['id'] is an array which you can easily loop through.
Many ids means you're looking for an array of ids, not id1, id2, id3 etc. An array allows you to access them virtually the same way as $id[1], $id[2] etc, but without the headache of needing to herd hundreds of independent variables.
There's also no need to assign each value from $_GET into its own variable, you can use those values directly from $_GET. They're not getting any better by assigning them into individual variables.
Assuming I understood correctly and you want all GET variables to be actual variables you can use, there's a function extract to do that.
However, as noted in the documentation:
Do not use extract() on untrusted data, like user input (i.e. $_GET,
$_FILES, etc.). If you do, for example if you want to run old code
that relies on register_globals temporarily, make sure you use one of
the non-overwriting flags values such as EXTR_SKIP and be aware that
you should extract in the same order that's defined in variables_order
within the php.ini.
So basically you should not do this unless you have good reasons, and be careful if you do as to not overwrite any existing values.
However, if your alternative is to do this:
foreach($_GET as $key => $value) {
$$key=$value;
}
then extract is certainly better, as a) you can set it to not overwrite any existing variables, and b) you can have a prefix, so those imported variables can be distinguished. Like this:
extract ( $_GET, EXTR_SKIP);
For $user, $mode, $id which don't overwrite anything, or
extract ( $_GET, EXTR_PREFIX_ALL, 'user_input' );
for $user_input_mode, $user_input_user, $user_input_id etc.
function getIDs()
{
$ids = array();
if(isset($_GET['id']))
{
foreach($_GET['id'] as $key => $value)
{
$ids[$key] = $value;
}
}
return $ids;
}
If you can get your URL to send an array of id GET parameters to a PHP script you can just parse the $_GET['id'] array in the above function, assuming the URI looks like ?id[]=1&id[]=2&id[]=3
$ids = getIDs();
You can write
foreach($_GET as $key => $value) {
$$key=$value;
}
this will assign every key name as a varibale.
I've been working on trying to write a function that will grab the POST values of any given form submission, pop them into an array, loop through the array using trim, addslashes etcetera pass that value back to a variable where it can then be passed to a database.
Now the hurdle I have atm is getting all the input,textarea,select element data into an array upon form submission. code I have follows
$fields = array($_POST['1'], $_POST['2']);
$i = 0;
foreach ($fields as $field) {
$i++;
${'field'.$i } = trim(addslashes(strip_tags($field)));
echo "POST field info #". $i ." - ". ${'field'.$i }."<br />";
}
As you can see everything is fine here baring that the POST value names are still being in-putted statically, what I need is a way to get that POST data fed into a loop which dynamically calls the POST name using an increment variable and then pop all that data into the same array. Code I have tried follows.
for ($ii=0;$ii++;) {
foreach($_POST['$ii'] as $field) {
$fields = array($field);
}
}
$i = 0;
foreach ($fields as $field) {
$i++;
${'field'.$i } = trim(addslashes(strip_tags($field)));
echo "POST field info #". $i ." - ". ${'field'.$i }."<br />";
}
Now I know this wont work but I can sense I am relatively close, so I am wondering if any clever person can help me sort the last part out? I sadly am now going to sleep and wont be viewing this post for at least 9 hours, apologies.
Thanks in advance.
Dan.
$arrayOfPostValues = $_POST; // it already is an array
$arrayOfPostValues = array_map('strip_tags', $arrayOfPostValues);
$arrayOfPostValues = array_map('trim', $arrayOfPostValues);
Or, if you really, really want to use a loop:
foreach ($arrayOfPostValues as &$value) {
$value = trim(striptags($value));
}
I'd absolutely advise against the use of addslashes, it serves very little purpose. Use mysql_real_escape_string or prepared statements instead.
I'd also advise against breaking the vales out of the array into separate variables, it can only cause problems. If you really want to do it, there's the extract function, which does exactly that. But, again, don't do it. Arrays are the perfect way to handle this kind of data.
You need to assign values to $_POST[1] and $_POST[2] to begin with, I've done this for you but normally they would be populated from a form I assume?
I'm not sure why you want to do this sort of thing: ${'field'.$key}, but I've left that part as is as I assume you must have a reason.
Anyway I've modified your code a bit, see below.
$_POST['1'] = '<h1>variable 1</h1>';
$_POST['2'] = '<h2>variable 2</h2>';
foreach($_POST as $key => $value){
${'field'.$key} = trim(addslashes(strip_tags($value)));
echo "POST field info #". $key ." = ". ${'field'.$key}."<br />";
}
The above code outputs:
POST field info #1 = variable 1
POST field info #2 = variable 2
On a side note, using field names such as '1' and '2' is not very good. Try using something more descriptive but as I said above I assume you have a reason for doing this.
UPDATE:
You can still get this to work for any form even if you are using specific names for the form elements. I have added a few lines below as an example for you.
$_POST['email'] = 'example#example.com';
$_POST['password'] = 'hgbks78db';
$_POST['name'] = '';
foreach($_POST as $key => $value){
if($value==''){
echo 'POST field "'.$key . '" is empty<br />';
/* I added the name of the field that is empty to an error array
so you have a way of storing all blank fields */
$a_error[] = $key;
}
else{
echo 'POST field "'.$key . '" is not empty<br />';
}
}