I have the following post variables:
$line_1_09
$line_1_12
$line_1_15
$line_1_18
$line_1_21
$line_2_09
$line_2_12
$line_2_15
$line_2_18
$line_2_21
$line_3_09
$line_3_12
$line_3_15
$line_3_18
$line_3_21
I know from my previous form that of the 15 inputs(posts) 12 are populated. the 12 is stored in variable $populatedrows.
I then want to create a table on my new page
<table>
<?php for ($i=1; $i<=$populatedrows; $i++)
{
?>
<tr>
<td>
<input type="text" value="//first post with information//">
</td>
</tr>
<?php } ?>
</table>
so in this example, if $line_1_09
and $line_1_12
are empty, the first table row input must then be $line_1_15
and so it will continue 'looping' through the next available / populated post variables until the table is equal to $populatedrows
. this will be equal to the number of post variables that contain data.
Strange situation for me so not really sure how to go about it.
In case you just want to create input for each not empty $_POST variable:
<?php
foreach($_POST as $key => $value) //$key is e.g 'line_1_20'
{
// substr($key, 0, 5) == 'line_' checks if the $key starts with 'line_'
if((substr($key, 0, 5) == 'line_') && !empty($value))
{
?>
<tr>
<td>
<input type="text" value="<?php echo $value ?>">
</td>
</tr>
<?php
}
}
?>
If you want less then all populated $_POST:
<?php
$count = 0; //count rendered fields
foreach($_POST as $value)
{
if(!empty($value))
{
?>
<tr>
<td>
<input type="text" value="<?php echo $value ?>">
</td>
</tr>
<?php
$count++; //increase counter
}
if($count == $populatedrows) //if the coutner hits the requested amount break the loop
break;
}
?>
you can iterate your variable names, bit ugly :-) http://php.net/manual/en/language.variables.variable.php
Just do each one and test isset(), if so output it.
e.g. you can nest a couple of for loops to generate the indexes (1,2,3) and (9, 12, 15, 18, 21). then get your variables
$var_name = '$line_' . $i . '_' . $j;
echo ${$var_name};
You'll have to pad in the leading zero on $j for 9 -> 09
You may consider iterating through the post data, but your code then becomes broken if you change the amount or sequence of the post data being sent to the page.
If the data is not in the correct order for your table, put it into an array and then do the table write after.
Try this:
<table>
<?php for ($i=1; $i<=$populatedrows; $i++)
{
if(isset($_POST[$i])) {
?>
<tr>
<td>
<input type="text" value="<?php echo $_POST[$i] ?>">
</td>
</tr>
<?php }
} ?>
</table>
Give this a try?
<table>
<?php for ($i=1; $i<=$populatedrows; $i++) :
if (!empty($populatedrows)) continue;
?>
<tr>
<td>
<input type="text" value="//first post with information//">
</td>
</tr>
<?php endfor; ?>
</table>