DATA SUMMARY
I have the following data, an $existing_events
array of existing events and a request for a new event ($requested_start
and $requested_end
). Normally pulled from SQL, but I've replicated the issue here w/ static arrays:
$existing_events = array(
0 => array(
'time_start' => '2015-09-05 11:30:00',
'time_end' => '2015-09-05 18:45:00'
),
1 => array(
'time_start' => '2015-09-05 07:15:00',
'time_end' => '2015-09-05 10:30:00'
)
);
$requested_start = strtotime('2015-09-05 3:30:00 AM');
$requested_end = strtotime('2015-09-05 9:30:00 AM');
RESULTS ARRAY
A $results
array for tracking how many times the comparison is made ('comparison_counter') and how many conflicts are discovered ('conflicts'):
$results = array(
'conflicts' => 0,
'comparison_counter' => 0
);
FOREACH LOOP
And finally, before dumping out json_encode'd results, the foreach loop that compares start & end time for the requested new event, against start & end time for each preexisting event, using this logic. Note the comparison_counter
and conflict
increments—the former runs every time the loop runs, and the latter is only "reached" in its if-statement, when there is a conflict between the requested event time and the current event time being tested.
if (!empty($existing_events)){
foreach ($existing_events as $existing_event){
$existing_start = strtotime($existing_event['time_start']);
$existing_end = strtotime($existing_event['time_end']);
$results['comparison_counter']++;
if ($requested_start > $existing_end) {
break;
} elseif ($requested_end < $existing_start) {
break;
} else {
$results["conflicts"]++;
}
}
}
echo json_encode($results);
exit;
ACTUAL RESPONSE
What I receive, though, makes it appear that the foreach loop is only executing once, despite the fact that there are two items in my $existing_events
array. Here's what I receive with the data above:
comparison_counter: 1
conflicts: 0
vs. what I expect:
comparison_counter: 2
conflicts: 1
Oddly, as soon as I make the following change to 11:30 start-time(to attempt to overlap with both events):
$requested_end = strtotime('2015-09-05 11:30:00 AM');
...the comparison_counter
now works. I now receive the following:
comparison_counter: 2
conflicts: 2
MY QUESTION
Why does the foreach loop not function properly, based on what's in the array I pass? I would expect it to at least hit its $results['comparison_counter']++;
every time it fires.