1

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?

2
  • 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. Commented Jun 26, 2012 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. Commented Jun 26, 2012 at 22:32

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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'};

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.