This code loops though an array of events, each with a start and end time... and simply sets a 'match' key to say that it has matched another event (i.e. a collision to resolve):
<?php
$results = array(
array('from' => 1, 'to' => 3),
array('from' => 3, 'to' => 6),
array('from' => 7, 'to' => 9),
array('from' => 4, 'to' => 8),
);
$k = 0;
foreach ($results as $p_id => $p_result) {
foreach ($results as $c_id => $c_result) {
if ($p_id == $c_id) {
continue;
}
$k++;
if ($p_result['from'] < $c_result['to'] && $p_result['to'] > $c_result['from']) {
$results[$p_id]['match'] = $c_id;
break;
}
}
}
print_r($results);
echo $k;
?>
By itself this isn't necessarily slow, but might be when thousands of events are being checked... i.e. using the DateTime object or UNIX timestamp for events though-out the year.
Trying with 3000 randomised events on my computer takes about 1 second with the "break" and 3 seconds without.
The to/from collision check itself is inspired by: Comparing date ranges
The main issue I see is that once event 1 has been checked against events 2-4, then events 2-4 don't really need to check themselves against 1:
$results[$p_id]['match'] = $c_id;
$results[$c_id]['match'] = $p_id;
But I can't think of an elegant way to work though this without making the code much harder to read.
One possibility is to create a new array of those events that have "passed" the checks, but I suspect the memory management of adding/removing elements on an array is much more than doing simple integer checks.