0

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];
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
David Passmore
  • 6,089
  • 4
  • 46
  • 70
  • `Index = (dayOfCycle - (count(events)-1))` – RiggsFolly Apr 30 '22 at 14:08
  • Related: https://stackoverflow.com/q/11764496/2943403, https://stackoverflow.com/q/24998261/2943403, https://stackoverflow.com/q/32716344/2943403, https://stackoverflow.com/q/27947074/2943403, https://stackoverflow.com/q/31141779/2943403, https://stackoverflow.com/q/16613857/2943403, https://stackoverflow.com/q/39373920/2943403 – mickmackusa May 26 '22 at 04:33

1 Answers1

2

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

KIKO Software
  • 15,283
  • 3
  • 18
  • 33