1

I need to get time sum in normal format, im trying like this

$total_extra += $arr['extra'][$i]
echo $total_extra; 

['extra'] time format is example "10:30"

I getting only hours in sum without min example "20", but i need full sum format like in "hours:mins"

andrew
  • 9,313
  • 7
  • 30
  • 61
SkySonny
  • 105
  • 2
  • 10
  • PHP doesn't add times and intervals like this. You need the [DateTime class](http://php.net/manual/en/class.datetime.php) –  Oct 14 '14 at 23:51
  • 1
    I suggest converting your times to a base unit (e.g. seconds) and then adding those up instead. – Dai Oct 14 '14 at 23:52
  • @RK. $total_extra += $arr['extra'][$i] is in the for loop. – SkySonny Oct 15 '14 at 00:12

1 Answers1

0

Convert everything to minutes (using explode() is what you need here), do the math, then convert it back to "hour:min".

$a = '10:30';
$b = '4:20';

$aExploded = explode(':', $a);
$bExploded = explode(':', $b);

$aMinutes = $aExploded[0]*60 + $aExploded[1];
$bMinutes = $bExploded[0]*60 + $bExploded[1];

$sum = $aMinutes + $bMinutes;

$sumString = floor($sum / 60).':'.($sum % 60);

echo $sumString;
Roman Pietrzak
  • 635
  • 3
  • 15
  • or you could just use `DateInterval` – andrew Oct 15 '14 at 00:08
  • But if i have single variable time? i just need to use only $a variant? because $arr['extra'][$i] is in the for loop and i need sum from all times. – SkySonny Oct 15 '14 at 00:10
  • @SkySonny: I just gave you and example of solution. You need to use it in your own way... Use the $sum of minutes through all your loop cycles - this should work. – Roman Pietrzak Oct 15 '14 at 01:33