Reputation: 109
How can I loop through each of these variable within a for loop?
$prod1 = $_POST['Option1']; //get input text
$prod2 = $_POST['Option2']; //get input text
$prod3 = $_POST['Option3']; //get input text
$prod4 = $_POST['Option4']; //get input text
for ($i=1; $i < 5; $i++) {
$prod = $prod . $i;
}
when I echo $prod . $i inside the loop, I want it to display the variable value.
Upvotes: 0
Views: 136
Reputation: 61849
You can loop through the $_POST
variable - it's an array.
foreach ($_POST as $prod)
{
echo $prod;
}
(Obviously if there are other values in the $_POST
array then you would need to check the key name first before deciding to use it.)
N.B. We don't know the source of this data (is it a HTML form) but it might make more sense for them to be submitted inside a single array to begin with - so all of the values would be accessed through $_POST["options"]
for example, and you'd just loop through that specific list.
Upvotes: 0
Reputation: 2904
You should be better off with storing your data in an array and then looping over the array:
$products = [
$_POST['Option1'],
$_POST['Option2'],
$_POST['Option3'],
$_POST['Option4']
];
foreach ($products as $prod ) {
echo $prod;
}
Alternatively, You can also iterate over the POST directly:
for ($i=1; $i < 5; $i++) {
echo $_POST['Option' . $i];
}
Upvotes: 1