phparraystimedifference

Calculate difference between each time value in a flat array


I'm having issues looping through an array and comparing each value to the next. Currently my function works, but it only compares values in sets of two. For example if in the 'Start' value I had:

1:05am 1:10am 1:30am 1:35am

I would get the results of: 5 minutes (The time between 1:05 and 1:10) and 5 minutes (The time between 1:30 and 1:35)

But I'm missing the time between 1:10 and 1:30. The next loop would give me the time between the next two values, ignoring the time between 1:35 and the next. The function is for silverstripe which uses datalists but the pattern should be the same as any array? Would appreciate any insight.

 function timeCount()
{
    $times = $this->Meetings()->sort('Start');
    $lastTime = null;

    foreach ($times as $time) {
        if ($lastTime == null) {
            $lastTime = $time;
            continue;
        }

        $time = strtotime($time->Start);
        $lastTime = strtotime($lastTime->Start);

        //For debugging
        $diff = round(abs($time - $lastTime) / 60, 2) . " minute | ";

        $lastTime = null;

        var_dump($diff);
    }
}

Solution

  • When you do

        $lastTime = null;
    

    It will cause the next iteration of the loop to think it is the first, therefore you're skipping every second comparison.

    function timeCount()
    {
        $times = $this->Meetings()->sort('Start');
        $lastTime = null;
    
        foreach ($times as $time) {
            if ($lastTime == null) {
                $lastTime = $time;
                continue;
            }
    
            $timeVal = strtotime($time->Start);
            $lastTimeVal = strtotime($lastTime->Start);
    
            //For debugging
            $diff = round(abs($timeVal - $lastTimeVal) / 60, 2) . " minute | ";
    
            $lastTime = $time;
    
            var_dump($diff);
        }
    }