PHP计算产生负数?

with the following values:

$a[0] = "4:00:00 am"
$b[0] = "8:00:00 am"
$c[0] = "9:00:00 am"
$d[0] = "1:22:00 pm"

why would the second if statement result in a -8 value being written to database? The first if statement results in the appropriate 4 hours value, but not the second. Is it because of the am/pm change or something?

if (!$a[0]=="" AND !$b[0]=="") {
   $start = explode(':', $a[0]);
   $end = explode(':', $b[0]);
   $total_hours = $end[0] - $start[0] - ($end[1] < $start[1]);
   mysqli_query($con,"UPDATE timeclock SET daily_hours='$total_hours' WHERE idex='$data[idex]' AND date='$date' AND status='slunch'");
}

if (!$c[0]=="" AND !$d[0]=="") {
   $start = explode(':', $c[0]);
   $end = explode(':', $d[0]);
   $total_hours = $end[0] - $start[0] - ($end[1] < $start[1]);
   mysqli_query($con,"UPDATE timeclock SET daily_hours='$total_hours' WHERE idex='$data[idex]' AND date='$date' AND status='ework'");
}

Because 1pm - 9am is the equivalent of 1 - 9, which is -8. You need to convert your PM times to a 24 hour clock, e.g.

1pm -> 13
9am -> 9

13 - 9 = 4

Your code is working exactly as it is supposed to. It's just that you're subtracting the time without converting it to 24-hour format.

You can use date() to do the conversion, like so:

$time_in_24 = date("H:i", strtotime("1:22:00 pm")); // 13:22

Change your code to:

$a[0] = date("H:i", strtotime("4:00:00 am"));  
$b[0] = date("H:i", strtotime("8:00:00 am"));  
$c[0] = date("H:i", strtotime("9:00:00 am"));  
$d[0] = date("H:i", strtotime("1:22:00 pm"));  

and that should fix it.

Codepad: http://codepad.org/jsltDXK0

$a[0] = "4:00:00 am";
$b[0] = "8:00:00 am";
$c[0] = "9:00:00 am";
$d[0] = "1:22:00 pm";
if (!$a[0]=="" AND !$b[0]=="") {
   $start = convert($a[0]);
   $end = conver($b[0]);
   $total_hours = $end[0] - $start[0] - ($end[1] < $start[1]);
   mysqli_query($con,"UPDATE timeclock SET daily_hours='$total_hours' WHERE idex='$data[idex]' AND date='$date' AND status='slunch'");
}

if (!$c[0]=="" AND !$d[0]=="") {
   $start = convert($c[0]);
   $end = convert($d[0]);
   $total_hours = $end[0] - $start[0] - ($end[1] < $start[1]);
   mysqli_query($con,"UPDATE timeclock SET daily_hours='$total_hours' WHERE idex='$data[idex]' AND date='$date' AND status='ework'");
}

function convert($hour){
    $m = strtolower(substr($hour, -2));//am or pm
    $hr = array_slice(explode(':', $hour), 0, 2);
    if ($m == 'pm') $hr[0] += 12;
    return $hr;
}