Waxi
Waxi

Reputation: 1651

Better way of looping through form inputs?

I have a form with inputs that can be dynamically added with a button click. The name/id of these inputs are setup to take advantage of arrays in PHP (read about this trick), but I don't prefer this method because it just doesn't feel right and because I wanted to do it how I originally thought of, but encountered issues when I tried. I could use some guidance because I'm over-thinking this. This is what I have at the moment...

HTML

<input name="specs[1][number]" id="specs[1][number]" type="text" placeholder="Specs..." />

PHP

$specCounter = count($_POST[specs]);

for ($i = 1; $i <= $specCounter; $i++) {

    echo '<li>' . $_POST[specs][$i][number] . '</li>';

};

As you can see, it's pretty straight forward; I have an array called specs and the value of the input will eventually be placed into the number slot.

But what I originally wanted, was something like this:

HTML

<input name="specs1" id="specs1" type="text" placeholder="Specs..." />
<input name="specs2" id="specs2" type="text" placeholder="Specs..." />

The problem I'm having is looping through these in PHP, because I don't know how to get a count of these inputs...

PHP

var myTotal = 'total inputs that have specs in the name/id';

for (var i = 1; i < myTotal; i++) {
    echo $_POST['specs' . i];
};

At the time of this writing, it dawned on me that maybe I should explore regular expressions, but maybe not? Any help is appreciated.

Upvotes: 0

Views: 73

Answers (4)

Oleg Dubas
Oleg Dubas

Reputation: 2348

$i = 1;
while(isset($_POST['specs'.$i]))
{
    echo $_POST['specs'.$i];
    $i++;
}

Also another way to put this:

for($i=1; isset($_POST['specs'.$i]); $i++) 
{
    echo $_POST['specs'.$i];
}

Whichever you prefer

Or if your numbers are not continuous:

foreach($_POST as $key => $value) {
    if(substr($key) === 'specs') {
        echo $value;
    }
}

Upvotes: 2

AbraCadaver
AbraCadaver

Reputation: 78994

The first way using arrays is normally preferred. I would simplify it though:

HTML

<input name="specs[1]" type="text"..." />
<input name="specs[2]" type="text"..." />

PHP

foreach($_POST['specs'] as $key => $val) {
    echo "specs $key is $val";
}

Unless you need them, you don't even have to specify the indexes, they will be created automagically:

<input name="specs[]" type="text"..." />
<input name="specs[]" type="text"..." />

Upvotes: 0

kaseOga
kaseOga

Reputation: 781

Maybe you want to use foreach instead a for:

foreach($_POST[specs] as $spec) {
    echo '<li>' . $spec['number'] . '</li>';
}

Upvotes: 0

KyleK
KyleK

Reputation: 5056

It's possible to do this:

foreach($_POST as $key => $value) {
    if(substr($key) === 'specs') {
        echo $value;
    }
}

Upvotes: 1

Related Questions