Reputation: 13
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?
Upvotes: 1
Views: 125
Reputation: 7525
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);
Upvotes: 5