1

i was wondering if there is any way that i can reference to an existing variable outside the loop

I currently have 50 variables that i am getting of a form they contain a "nr_" part and after that it is counting from 1 to 50 and i also have the $_POST variables of that. I now want to pass that into a for loop to get form input fields for each variable with a set value ($nr_1-50).

this is my current state:

for ($x = 1; $x <= 50; $x++) {
    echo "<tr><input type='number' name='nr_" . $x . "' value='" . $nr_1 . "'></tr>";
}

Maybe you can help me

Thank you in advance

EDIT:

i solved the problem as follows:

//created an array

$sticker_nr = array();

//inserted the $_POST values with a digit counting to 50 ($x)

for($x = 1; $x <= 50; $x++){
$sticker_nr[$x] = $_POST[$x.'_nr'];
}


//now i am able to output the array values in a loop
for ($x = 1; $x <= 50; $x++) {

echo "<input type='number' name='".$x."_nr' value='". $sticker_nr[$x] ."' 
>";
}

//Thank you again for the response
2
  • Does this answer your question? How to concatenate PHP variable name? Commented Jan 10, 2020 at 13:37
  • Have you tried the arrays for this problem? somethings like $arr[nr][1]? Commented Jan 10, 2020 at 13:39

1 Answer 1

0

Why use 50 variables when you could use an array with 50 entries?

$numbers = [];
for($x = 1; $x <50 $x++){
    $numbers[$x] = $_POST['nr_'.$x];
}
Sign up to request clarification or add additional context in comments.

3 Comments

thank you for your response i just changed some code in my project to generate the input based on a loop. i created an array called $numbers without values after that i started the loop but there is an error entering the $_POST[''] values into the array
@LeonWetterich Check what data your're actually getting in the POST. I normally use something like print_r($_POST); to check that the data I'm trying to use is what I'm expecting.
thank you again @Andrew Davie needed to think about that one but i now have a value in my array.

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.