'Repeating/Circular Array Lookup (when sought index is greater than highest index)
Before I go any further, I know the title may be completely ambiguous and that this has bound to of been asked before, however I just can't articulate it better presently nor can I think of a known name of the process I am trying to perform.
The context of this question is an array of recurring daily events which repeat indefinitely until a set end date.
Essentially, given an array of these daily events I need a piece of code that can say for day n return the event that would occur on said day. Where day n could be greater than the count of daily events in the original array.
So, given the example of 5 events in the array and day n = 8
it would return index 2 of the array.
Edit for clarity: Let me given a worked code example:
$events = ['event 1', 'event 2', 'event 3'];
$dayOfCycle = 12;
echo eventForDay($events, $dayOfCycle); // should echo 'event 3'
echo eventForDay($events, 8); // should echo 'event 2'
I need a function that loops and repeats over the $events
array until it reaches the relative index
Thinking through this in my head it would be something like this, but I'm sure there will be a much better way of doing it:
function eventForDay($events, $dayOfCycle){
$counter = 0;
for($i = 1; $i <= $dayOfCycle; $i++){
if($i >= count($events)){
$counter = 0;
}else{
$counter++;
}
}
return $events[$counter];
}
Solution 1:[1]
That's called a modulo operator.
Simply do:
function eventForDay($events, $dayOfCycle){
return $events[--$dayOfCycle % count($events)];
}
This will return the wanted result. See: PHP fiddle
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | KIKO Software |