0

Hi I have the following:

$q1 = $_POST["q2"];
$q2 = $_POST["q2"];
$q2 = $_POST["q2"];

What I'd like to do is put this within a For loop, as follows:

for ($i=1; $i<=3; $i++){
    $q1 = $_POST["q".$i.""];
}

I can add the variable to the POST part no problems but I cannot work out how to have the 1 next to the $q as a variable:

$q1 = $_POST["q".$i.""];

I'm sure it's simple but I cannot fathom it!

1
  • this should work $_POST["q".$i] Commented Jul 25, 2013 at 10:22

6 Answers 6

1

try this

$q_arr = array(); //create empty array
for ($i=1; $i<=3; $i++){
    if(isset($_POST["q".$i])) //first check existance of $_POST item with wanted key 
    $q_arr['q'.$i] =  $_POST["q".$i]; //store it in array

}
extract($q_arr);  //extract creates variables naming them as their key 
if(isset($q1)) //just for test 
echo $q1; //just for test 
Sign up to request clarification or add additional context in comments.

Comments

1

Check the 'variable variables' feature available in php here. Your code will be similar to this:

$varName  = 'q' . $i;
$$varName = $_POST[$varName]

Also, check out the extract function

3 Comments

This would work, but it just feels wrong to do it this way unless you are forced to not use array for some reason. +1 for a valid answer, though not one I agree with.
i agree with you, variable variables are never safe
Thanks but wanted to avoid using variable variables if poss.
1
for ($i=1; $i<=3; $i++){
    ${"q$i"} = $_POST["q$i"];
}
echo $q1;

Using variable variables can easily assign $q1

Comments

1

Do you mean this:

// As array:
$q[ $i ] = $_POST['q'.$i]; // this one is my prefered

// Or as object:
$q->$i = $_POST['q'.$i];

edit: removed the eval() version, You simply should not use that. The array one should work just fine :)

You cán use variable variables, but you shouldn't. It get very complicated real fast.

$name1 = 'myName'; 
$example = "name".$i;
echo $$example;

2 Comments

That did not work. $a='a'; $b='b'; echo $a.$b; will concat to 'ab' with a dot. I removed the example, it was bad practice anyway :)
Yap, I got the explanation :)
0

Would defining your $q variables as an array help?

$q[i] = $_POST["q".$i.""];

Comments

0

do you mean you want to create the variable names dynamically? like this:

for ($i=1; $i<=3; $i++){
   $varname = "q" . $i;
   $$varname = $_POST["q".$i.""];
}
print $q2;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.