Saadia Saadia - 6 months ago 12
PHP Question

Unable to compare two dates

I have an

array
and using
foreach
loop I am trying to check if the
dinner_date
matches the previous index
dinner_date
and if they don't i am assigning
yes
to variable called
$newDate
This is what the output looks line

array:4 [▼
0 => array:3 [▼
"request_id" => "48"
"dinner_date" => "2016-05-16T10:00:00"
"new_date" => "no"
]
1 => array:3 [▼
"request_id" => "51"
"dinner_date" => "2016-05-16T10:00:00"
"new_date" => "no"
]
2 => array:3 [▼
"request_id" => "50"
"dinner_date" => "2016-05-27T10:00:00"
"new_date" => "no"
]
3 => array:3 [▼
"request_id" => "52"
"dinner_date" => "2016-05-27T10:00:00"
"new_date" => "no"
]
]


This is my
foreach
loop

$dinnerDetails = array();
$lastDinnerDate = '';
$newDate = '';
foreach ($invitations as $invitation) {
$lastDinnerDate = $invitation['dinner_date'];
if ($invitation['dinner_date'] > $lastDinnerDate) {
$newDate = 'yes';

} else {
$newDate = 'no';
}

$dinnerDetails[] = array(
'request_id' => $invitation['request_id'],
'dinner_date' => $invitation['dinner_date'],
'new_dinner' => $newDate
);
}


So as you can see in index
2
of array output it says
new_date => no
it should actually be
yes
because
dinner_date
of this index is different than the
dinner_date
of the index above.

So am I doing wrong here?

Answer

Comment: In your case they both are same, you need to store $lastDinnerDate = $invitation['dinner_date']; after the condition.

Add one more condition $lastDinnerDate != "" to your if condition and assign the `` after the in condition.

For the comparison you need to convert the datetime into timestamp.

foreach ($invitations as $invitation) {

    if (strtotime($invitation['dinner_date']) > $lastDinnerDate && $lastDinnerDate != "") {
        $newDate = 'yes';

    } else {
        $newDate = 'no';
    }
    $lastDinnerDate = strtotime($invitation['dinner_date']);

    $dinnerDetails[] = array(
        'request_id' => $invitation['request_id'],
        'dinner_date' => $invitation['dinner_date'],
        'new_dinner' => $newDate
    );
}