-3

I have this array.

$val = array(12:10, 4:16, 2:05);

I want to subtract 14:00 hrs from the $val array in the way that from every element that element do not become negative like this:

$val = array(0, 2:26, 2:05)
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98

1 Answers1

0
<?php
$input = "14:00";
$val = array("12:10", "4:16", "2:05");

function timeSubtractionFirstTime($actual_time ,$time_to_reduce){
   $actual_time_array = explode(":",$actual_time);
   $time_to_reduce = explode(":",$time_to_reduce);
   $final_result = [];
   if($actual_time_array[1] < $time_to_reduce[1]){
     $actual_time_array[0] = $actual_time_array[0]-1;
     $final_result[] = $actual_time_array[1]+60-$time_to_reduce[1];
   }else{
     $final_result[] = $actual_time_array[1]-$time_to_reduce[1];
   }
    $final_result[] = $actual_time_array[0]-$time_to_reduce[0];

    return implode(":", array_reverse($final_result));
}

$timeToReduceLeft = $input;
foreach ($val as &$value) {
    $diff = timeSubtractionFirstTime($value, $timeToReduceLeft);
    if (strpos($diff, chr(45)) !== false){ //if $value < $timeToReduceLeft
        $timeToReduceLeft = timeSubtractionFirstTime($timeToReduceLeft, $value);
        $value = "00:00";
    }
    else { //if $value >= $timeToReduceLeft
        $value = timeSubtractionFirstTime($value, $timeToReduceLeft);
        $timeToReduceLeft = "00:00";
    }
    
    
    if ($timeToReduceLeft == "00:00"){
        break;
    }

}

echo implode(",", $val);

I get the function to extract time from this post and implement the logic for your problem as follows:

We substract the time from input value until the input value become zero or entire array elements become zero (by forloop).

This solution also works with input or array elements value greater than "24:00".