1

I am looking to do something like the following:

for ($i=0; $i<=$number_of_bundles; $i++) {

    $rug_size . $i = $_POST['Size' . $i];

}

Unfortunately this does not work since I get "undefined index" and when I try echoeing, for example, $rug_size1 is undefined.

How can something like this be done?

2
  • 2
    Whenever you think you want this, what you actually want is an array! Commented Dec 18, 2013 at 7:29
  • Thank you, I learned my lesson! Commented Dec 18, 2013 at 7:38

5 Answers 5

3

Assuming you initialize $rug_size as an array():

$rug_size[$i] = $_POST['Size' . $i];

If you really want to use different variable names (hopefully not):

$vn = 'rug_size' . $i;
$$vn = $_POST['Size' . $i];
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, this is a very simple and smart answer. Thank you!
2

schould work like this:

for ($i=0; $i<=$number_of_bundles; $i++) {
    $varname = 'rug_size'.$i;
    $$varname = $_POST['Size'.$i];
}

http://php.net/manual/en/language.variables.variable.php

Comments

2

You need wrap you dynamic variable within {} (and concat string with Dot), like:

<?php
$i = 1;
${"rug_size".$i} = "Hello world!";
echo $rug_size1;
?>

Output:

Hello world!

2 Comments

That doesn't work since it is inside of a for loop. Unexpected {.
Using ${} is a way to create dynamic variables
0

do like this .

for ($i=0; $i<=$number_of_bundles; $i++) {

    ${'rug_size' . $i} = $_POST['Size' . $i];
}

Comments

-1

if i am not wrong than

$_POST['Size' , $i]

will be(i.e. dot instead of comma)

$_POST['Size'. $i]

another way to avoid error:use isset()

for ($i=0; $i<=$number_of_bundles; $i++) {
if(isset($_POST['Size' . $i]))
 {
  $rug_size . $i = $_POST['Size' . $i];
 }
}

4 Comments

Sorry, for some reason I used a comma for my question. During my test I used the dot and it does not seem to work.
@RaphaelRafatpanah are you sure u have input type's name as size1,size2 and so on?
Yes, I am sure. Size with a capital S.
$rug_size . $i (as variable) should not work.If PHP really prompts undefined index I'll suggest you to check var_dump($_POST) or wrap it with a isset() checking.

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.