Reputation: 102
I want to check if any of the dates in the array will overlap the others. Only thing I want to know is if it true or false. It has to check if the start and stop time will overlap the time in the other rows.
This is an example of my arrays. In this case it should return false.
$testFalse = [
'row_0' => [
'startTime' => '2019-10-07 07:30:00',
'stopTime' => '2019-10-07 09:00:00'
],
'row_1' => [
'startTime' => '2019-10-07 07:30:00',
'stopTime' => '2019-10-07 08:00:00'
],
'row_2' => [
'startTime' => '2019-10-07 08:30:00',
'stopTime' => '2019-10-07 10:00:00'
],
];
In this case it should return true.
$testTrue = [
'row_0' => [
'startTime' => '2019-10-07 07:30:00',
'stopTime' => '2019-10-07 09:00:00'
],
'row_1' => [
'startTime' => '2019-10-07 09:00:00',
'stopTime' => '2019-10-07 10:00:00'
],
];
My current try is, but I wan't to combine this in a loop somehow:
//------------StartTime row-0--------------------
if (($array['row_0']['startTime'] >= $array['row_1']['startTime']) && ($array['row_0']['startTime'] <= $array['row_1']['stopTime'])){
var_dump('Is between');
}else{
var_dump('Not between');
}
if (($array['row_0']['startTime'] >= $array['row_2']['startTime']) && ($array['row_0']['startTime'] <= $array['row_2']['stopTime'])){
var_dump('Is between');
}else{
var_dump('Not between');
}
?>
Upvotes: 0
Views: 202
Reputation: 978
You can just check if one of the dates is between:
$testTrue = [
'row_0' => [
'startTime' => '2019-10-07 07:30:00',
'stopTime' => '2019-10-07 09:00:00'
],
'row_1' => [
'startTime' => '2019-10-07 09:00:00',
'stopTime' => '2019-10-07 10:00:00'
],
];
$testFalse = [
'row_0' => [
'startTime' => '2019-10-07 07:30:00',
'stopTime' => '2019-10-07 09:00:00'
],
'row_1' => [
'startTime' => '2019-10-07 07:30:00',
'stopTime' => '2019-10-07 08:00:00'
],
'row_2' => [
'startTime' => '2019-10-07 08:30:00',
'stopTime' => '2019-10-07 10:00:00'
],
];
function checkIntersections(array $arr): bool {
$count = count($arr);
for($i=0;$i < $count;$i++) {
$startDate = new DateTime($arr['row_'.$i]['startTime']);
$stopDate = new DateTime($arr['row_'.$i]['stopTime']);
for($j=0;$j < $count;$j++) {
if ($j === $i) continue;
$startDateCompare = new DateTime($arr['row_'.$j]['startTime']);
$stopDateCompare = new DateTime($arr['row_'.$j]['stopTime']);
if (
($startDate > $startDateCompare && $startDate < $stopDateCompare)
|| ($stopDate > $startDateCompare && $stopDate < $stopDateCompare)
) {
return false;
}
}
return true;
}
}
var_dump(checkIntersections($testTrue));
var_dump(checkIntersections($testFalse));
Upvotes: 2