Homer_J
Homer_J

Reputation: 3323

PHP Variable within For Loop

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!

Upvotes: 0

Views: 71

Answers (6)

Nikola Kirincic
Nikola Kirincic

Reputation: 3757

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 

Upvotes: 1

Martijn
Martijn

Reputation: 16123

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;

Upvotes: 1

user1646111
user1646111

Reputation:

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

Using variable variables can easily assign $q1

Upvotes: 1

pythonian29033
pythonian29033

Reputation: 5207

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;

Upvotes: 0

Richard A.
Richard A.

Reputation: 1157

Would defining your $q variables as an array help?

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

Upvotes: 0

Vitaly  Muminov
Vitaly Muminov

Reputation: 1952

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

Upvotes: 1

Related Questions