2

I have a set of text boxes like this:

<input type="text" name="tbxt[]" />
<input type="text" name="tbxt[]" />
<input type="text" name="tbxt[]" />

and I am using

foreach ($_POST['tbxt'] as $tbxt) {
    //
}

But for example if I have:

<input type="text" name="tbxt[]" /><select name="selxt[]"></select>
<input type="text" name="tbxt[]" /><select name="selxt[]"></select>
<input type="text" name="tbxt[]" /><select name="selxt[]"></select>

So can I write something like this:

foreach (($_POST['tbxt'] as $tbxt) && ($_POST['selxt'] as $selxt)) {
    //
}

Is this possible?

Kevin
  • 41,694
  • 12
  • 53
  • 70
Karthik Malla
  • 5,570
  • 12
  • 46
  • 89

2 Answers2

8

Looks like a case for SPL Multiple iterators:

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($_POST['tbxt']));
$mi->attachIterator(new ArrayIterator($_POST['selxt']));
foreach($mi as list($tbxt, $selxt)) {
    echo $tbxt, ' ', $selxt, PHP_EOL;
    ....
}

though the use of list() here requires PHP >= 5.5.0

You can simulate this in earlier versions by assigning a name to each iterator, then extracting within your loop:

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($_POST['tbxt']), 'tbxt');
$mi->attachIterator(new ArrayIterator($_POST['selxt']), 'selxt');
foreach($mi as $lists) {
    extract($lists);
    echo $tbxt, ' ', $selxt, PHP_EOL;
    ....
}

or

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($_POST['tbxt']), 'tbxt');
$mi->attachIterator(new ArrayIterator($_POST['selxt']), 'selxt');
foreach($mi as $lists) {
    echo $lists['tbxt'], ' ', $lists['selxt'], PHP_EOL;
    ....
}
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • 1
    wow this is amazing never seen this one before, i have a question. what happens if they don't have the same size? lets say `seltxt` has only 2 – Kevin Aug 09 '14 at 12:55
  • 1
    @Ghost, that's where you need to read the PHP docs, and look at the flags that can be applied to Multiple Iterators to handle that case... because there's different options you can apply to say how multiple iterators should behave in that case (see `predefined constants` in the docs). You can also control how the keys tie up; but it's certainly easier to use when you have the same number of entries in each, and you can link any number of arrays using Multiple Iterators, you're not just limited to 2 – Mark Baker Aug 09 '14 at 13:00
1

If you are willing to use for instead of foreach, you can do something like the following:

$tbxt = $_POST['tbxt'];
$selxt = $_POST['selxt']

for ($i=0; $i<sizeof($tbxt); $i++) {
    //access them using $tbxt[$i] and $selxt[$i]
}
StathisG
  • 1,159
  • 1
  • 10
  • 18