'Add values with same date in Php

I want to add values with same date. However, I'm confused on how to implement it to my code. The output of code below gets the total minutes together with its date. Can someone help me or give some advice with this?

Here's my code:

    while($row3 = mysqli_fetch_array($result2)){

        if(!empty($row3['time_outAM'])){
            $attend_timeoutfirst = date("H:i:s", strtotime($row3['time_outAM']));
            if($sched_timeoutfirst > $attend_timeoutfirst ){
                $start = strtotime($attend_timeoutfirst);
                $stop = strtotime($sched_timeoutfirst);
                $diff = ($stop - $start);
                echo  $total1 = abs($diff/60);  
                echo "<br>";
                echo $date = $row3['date'];
                echo "<br>";
            }
        }
        if(!empty($row3['time_outPM'])){
            $attend_timeoutsec = date("H:i:s", strtotime($row3['time_outPM']));
            if($sched_timeoutsec > $attend_timeoutsec){
                $start = strtotime($attend_timeoutsec);
                $stop = strtotime($sched_timeoutsec);
                $diff = ($stop - $start);
                echo $total2 = abs($diff/60);  
                echo "<br>";
                echo $date1 = $row3['date'];
                echo "<br>";
            }
        }
    }

Code Output:

30
2022-05-03
30
2022-05-04
10
2022-05-04
120
2022-05-09
70
2022-05-09

Expected Output:

30
2022-05-03
40
2022-05-04
190
2022-05-09
php


Solution 1:[1]

you can sum value of date outside for loop

while($row3 = mysqli_fetch_array($result2)){
    $total1 = 0;
    $total2 = 0;
    $date = '';
    $date1 = '';
    if(!empty($row3['time_outAM'])){
        $attend_timeoutfirst = date("H:i:s", strtotime($row3['time_outAM']));
        if($sched_timeoutfirst > $attend_timeoutfirst ){
            $start = strtotime($attend_timeoutfirst);
            $stop = strtotime($sched_timeoutfirst);
            $diff = ($stop - $start);
            $total1 = abs($diff/60); 
            $date = $row3['date'];
        }
    }
    if(!empty($row3['time_outPM'])){
        $attend_timeoutsec = date("H:i:s", strtotime($row3['time_outPM']));
        if($sched_timeoutsec > $attend_timeoutsec){
            $start = strtotime($attend_timeoutsec);
            $stop = strtotime($sched_timeoutsec);
            $diff = ($stop - $start);
            $total2 = abs($diff/60);  
            $date1 = $row3['date'];
        }
    }
    if($date == $date1){
        echo  $total1 +  $total2;  
        echo "<br>";
        echo $date;
        echo "<br>";
    }else{
        echo  $total1;  
        echo "<br>";
        echo $date;
        echo "<br>";
    }
}

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 Bhargav Chudasama