Kev
Kev

Reputation: 415

Increment a variable name in for loop

so I have a variable that I would like to set based on some submitted form data. On the form I have a set of fields that the user can increase the number of (that is, they can add more of the same type of field), and so I need to set the script that handles the submitted data to accomodate this.

So far this is what I have:

while ($i <= $totalproducts) {

       $product.$i = $_POST['product'.$i];
       $i++;

    }

$totalproducts holds the total number of fields. As an example, let's say I had 3 items, here's what I would like to get from the code:

$product1 = $_POST['product1'];
$product2 = $_POST['product2'];
$product3 = $_POST['product3'];

I'm sure I'm close, just can't quite slot it together...

Upvotes: 1

Views: 391

Answers (2)

Pavel Štěrba
Pavel Štěrba

Reputation: 2912

You can use variable variable:

while ($i <= $totalproducts) {
   $variable = 'product' . $i;

   $$variable = $_POST['product' . $i];
   $i++;
}

But better will be use array:

$products = array();
while ($i <= $totalproducts) {
   $products[$i] = $_POST['product' . $i];
   $i++;
}

Upvotes: 3

kero
kero

Reputation: 10638

You need to do it like this

${$product.$i} = $_POST['product'.$i];

but this is bad style imo. Why don't you use an array? This is exactly what arrays are for.

Also arrays have many advantages. Want to know how many products there are? Easy, just count(). Want to pass the products to say another function? Easy, just pass the array and not an unknown number of variables, etc.

Upvotes: 2

Related Questions