Iterate over 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> Suppose I have a few lines of code above. How to iterate and get the value for $_POST['fullname'] and $_POST['job_title'] ?
This is just an array:
foreach ($_POST['fullname'] as $name) { echo $name."\n"; } If the problem is that you want to iterate over two arrays in sequence, just use one of them to get the indices:
for ($i=0; $i < count($_POST['fullname']); $i++) { echo $_POST['fullname'][$i]."\n"; echo $_POST['job_title'][$i]."\n"; } I deleted this before, as 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 source 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 general information. With SPL DualIterator, you can do 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(); } I think the problem you are trying to solve gets a pair of values ββfrom $ _POST ['fullname'] [] and $ _POST ['jobtitle'] [], which have the same index.
for ($i = 0, $rowcount = count($_POST['fullname']); $i < $rowcount; $i++) { $name = $_POST['fullname'][$i]; // get name $job = $_POST['jobtitle'][$i]; // get jobtitle } If you understand correctly, you have 2 arrays that you basically want to repeat in parallel.
Something like below may work for you. Instead of $a1 and $a2 use $_POST['fullname'] and $_POST['jobtitle'] .
<?php $a1=array('a','b','c','d','e','f'); $a2=array('1','2','3','4','5','6'); // reset array pointers reset($a1); reset($a2); while (TRUE) { // get current item $item1=current($a1); $item2=current($a2); // break if we have reached the end of both arrays if ($item1===FALSE and $item2===FALSE) break; print $item1.' '. $item2.PHP_EOL; // move to the next items next($a1); next($a2); } The answers of Vinko and OIS are excellent (I parsed OIS). But if you always print 5 copies of text fields, you can always simply specify each field:
<?php $i=0; while($i < 5) { ?><tr> ... <input name="fullname[<?php echo $i; ?>]" type="text" class="txt w90" id="fullname[<?php echo $i; ?>]" value="<?php echo $value; ?>" />