Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm relatively new to PHP loops, been learning them and they sure do make my life easier. However, I came across a bit of a struggle when trying to create a new variable for the PHP loop.

Background:

I declared 21 variables such as:

$q1W = 5;
$q2W = 10;
$q3W = 2;

Then I grabbed the $_GET (q1,q2,q3) variables and put them into variables with their values:

foreach($_GET as $qinput => $value) {
    $$qinput  = $value ;
}

Now, essentially, I want to turn this code:

$q1final = $q1 * $q1W;
$q2final = $q2 * $q2W;
$q3final = $q3 * $q3W;

Into a loop so I don't need to type out that all the way to 21. This is what I have thus far:

<?php for ($i=1; $i<=21; $i++) { 
$q.$i.final = $q.$i * $q.$i.W
}

What am I missing?

share|improve this question
    
You can't concatenate when making dynamic variables the same way as normal (periods). Also, generally if you have to use dynamic variables, you're doing something wrong. –  John V. Jun 26 '12 at 22:28
1  
@AlexLunix You can concatenate strings to make dynamic variable names (see my comment on the answer below) but I agree that if "dynamic variable names" is the right answer, you're probably asking the wrong question. –  DaveRandom Jun 26 '12 at 22:32

1 Answer 1

I would recommend using arrays instead of lots of variables. It makes relating your data more straightforward. For example:

$mults = array(
    'q1W' => 5, 
    'q2W' => 10,
    'q3W' => 2
);
$final = array();
foreach ($_GET as $qinput => $value) {
    $final[$qinput] = $mults[$qinput] * $value;
}
print_r($final);
share|improve this answer
2  
This is the correct answer (+1), but for reference to the OP/future visitors, the correct syntax for using a counter as above to define a variable variable name would be use strings in braces, e.g. ${'q'.$i.'final'} = ${'q'.$i} * ${'q'.$i.'W'}; –  DaveRandom Jun 26 '12 at 22:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.