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

1 Answers1

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];
}
Andrew Davie
  • 131
  • 3
  • 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 – Leon Wetterich Jan 10 '20 at 15:11
  • @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. – Andrew Davie Jan 10 '20 at 15:15
  • thank you again @Andrew Davie needed to think about that one but i now have a value in my array. – Leon Wetterich Jan 10 '20 at 17:04