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.

2 Answers 2

Try with this:

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

echo $color_1;
echo $color_2;
    
That's it ! Thank you very much, @kip – blueway 2 hours ago
    
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 2 hours ago
    
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 2 hours ago
    
Thanks again, the issue is solved. – blueway 2 hours ago

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.

    
Thanks for your answer, I got an error when I tested the code with the following variables ($color_1, $color_2). Output: i.cubeupload.com/gtzjje.png – blueway 3 hours ago
    
My codes: i.cubeupload.com/pLY1bD.png – blueway 3 hours ago