Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating multiple $_POST arrays

I have the following code:

<tr>
    <td width="60%">
        <dl>
            <dt>Full Name</dt>
            <dd>
                <input name="fullname[]" type="text" class="txt w90" id="fullname[]" value="<?php echo $value; ?>" />
            </dd>
        </dl>
    </td>
    <td width="30%">
        <dl>
            <dt>Job Title</dt>
            <dd>
                <input name="job_title[]" type="text" class="txt w90" id="job_title[]" value="<?php echo $value2; ?>" />
            </dd>
        </dl>
    </td>
</tr>

Lets assume that I have several rows of the above code. How do I iterate and get the value for arrays $_POST['fullname'] and $_POST['job_title']?

like image 789
aeran Avatar asked Dec 07 '22 08:12

aeran


2 Answers

It's just an array:

foreach ($_POST['fullname'] as $name) {
    echo $name."\n";
}

If the problem is you want to iterate over the two arrays in parallel simply use one of them to get the indexes:

for ($i=0; $i < count($_POST['fullname']); $i++) {
    echo $_POST['fullname'][$i]."\n";
    echo $_POST['job_title'][$i]."\n";
}
like image 156
Vinko Vrsalovic Avatar answered Dec 28 '22 06:12

Vinko Vrsalovic


I deleted this earlier since it was pretty close to Vinko's answer.

for ($i = 0, $t = count($_POST['fullname']); $i < $t; $i++) {
    $fullname = $_POST['fullname'][$i];
    $job_title = $_POST['job_title'][$i];
    echo "$fullname $job_title \n";
}

With original index not numerical from 0 - N-1

$range = array_keys($_POST['fullname']);
foreach ($range as $key) {
    $fullname = $_POST['fullname'][$key];
    $job_title = $_POST['job_title'][$key];
    echo "$fullname $job_title \n";
}

This is just for general info. With SPL DualIterator you can make something like:

$dualIt = new DualIterator(new ArrayIterator($_POST['fullname']), new ArrayIterator($_POST['job_title']));

while($dualIt->valid()) {
    list($fullname, $job_title) = $dualIt->current();
    echo "$fullname $job_title \n";
    $dualIt->next();
}
like image 31
OIS Avatar answered Dec 28 '22 05:12

OIS