Reputation: 212
I have created a form which takes dates as arrays:
<form action="" enctype=”multipart/form-data” method="post" >
Date1 <input type="date" name="tst1[]">
</div>
<div id="div2">
Date2 <input type="date" name="tst2[]">
</div>
<input type="submit" value="test" name="submit">
</form>
JavaScript:
var x=1
function appendRow1()
{
var d = document.getElementById('div1');
d.innerHTML += '<input type="date" name="tst1[]"/>';
}
var x=1
function appendRow2()
{
var d = document.getElementById('div2');
d.innerHTML += '<input type="date" name="tst2[]"/>';
}
I am trying to subtract the dates that the user inputs in such a way that the dates at position 1 of both arrays get subtracted but the code subtracts all the dates in all combinations.
php:
(isset($_POST['submit']) && is_array($_POST) == "test") {
foreach($_POST['tst1'] as $date1){
foreach ($_POST['tst2'] as $date2){
$diff = abs(strtotime($date2) - strtotime($date1));
echo $diff;
$years = floor($diff / (365*60*60*24));
$yy[] = $years;
$average = array_sum($yy)/count($yy);
echo $average . '<br>';
Upvotes: 0
Views: 51
Reputation: 789
If you only need to subtract the position 1 of each array you can directly access the position without iterating the whole array:
$date1 = $_POST['tst1'][1];
$date2 = $_POST['tst2'][1];
If you want to subtract elements in the same position of both arrays you might use a for loop because it instantiates an iterator variable that you can use to set a position at both arrays.
Lets consider that both arrays have the same size.
$date1 = $_POST['tst1'];
$date2 = $_POST['tst2'];
for($i = 0; $i < sizeof($date1); $i++){
$diff = abs(strtotime($date2[$i]) - strtotime($date1[$i]));
//...
}
Upvotes: 2