0

According to the value of count variable ($count = 3), I need to get output like this.

$color_1 = $_POST["color-1"];
$color_2 = $_POST["color-2"];
$color_3 = $_POST["color-3"];

I tried this method but it did not work.

for ($i = 1; $i <= $count; $i++) {
    $color_.$i = $_POST["color-.$i"];
}

Thanks so much for your helps & interestings.

blueway
  • 129
  • 7

2 Answers2

0

You need to join your name and variable via curly brackets. If not you just try to use the value of your variable $i.

for ($i = 1; $i <= $count; $i++) {    
    ${"color_" . $i} = ${_POST["'color-" . $i . "'"]};
}

Check this example out.

GePu
  • 320
  • 2
  • 13
  • Thanks for your answer, I got an error when I tested the code with the following variables ($color_1, $color_2). Output: http://i.cubeupload.com/gtzjje.png – blueway Jul 23 '17 at 01:03
0

Try with this:

for ($i = 1, $count = count($_POST); $i <= $count; $i++) {
    ${"color_{$i}"} = $_POST["color-{$i}"];
}

echo $color_1;
echo $color_2;
kip
  • 1,120
  • 7
  • 11
  • But, there is such a problem. When i add another input to the form, I get this error. Notice: Undefined index: prod-color-3 in C:\xampp\htdocs\phptest\index.php on line 66 – blueway Jul 23 '17 at 01:48
  • If the other input not has a name like `prod-color-*` the for loop is failure because I count all values of POST `$count = count($_POST)`, change `$count` to the number of inputs with name like `prod-color-*` – kip Jul 23 '17 at 01:52