0

my code

    if($hours==0){
        $late_absent += 1;
        $is_late = $hours . ":" . $minutes . "";                 
    }else{
        $late_absent += 1;
        $is_late = $hours . ":" . $minutes . "";                 
    }
       }else{

       $is_late = '-';
    

Expected results

| Time  | 
| 07:33 |
| 00:15 |

Current results

| Time | 
| 7:33 |
| 0:15 |

I want to add leading 0 in hours

Babo
  • 357
  • 3
  • 13
  • 1
    Does this answer your question? [Display number with leading zeros](https://stackoverflow.com/questions/134934/display-number-with-leading-zeros) – Andrea Olivato Mar 15 '22 at 03:22
  • 1
    Try `$is_late = str_pad($hours, 2, '0', STR_PAD_LEFT) . ':' . str_pad($minutes, 2, '0', STR_PAD_LEFT);` and see if that helps. – zedfoxus Mar 15 '22 at 03:28
  • @Babo. I have added an example that you can adapt to your needs. – zedfoxus Mar 15 '22 at 04:01

1 Answers1

1

I should probably add this as an answer so someone can find it later. Use str_pad to your advantage here.

You have minutes and hours, both of which could be a 1-digit or 2-digits number. Design your code to account for that. Let's see the code. You can adapt it to your needs.

<?php

function formattedTime ($hours, $minutes) {
    return str_pad($hours, 2, '0', STR_PAD_LEFT) . ':' . str_pad($minutes, 2, '0', STR_PAD_LEFT) . "\n";
}

$hours = 7;
$minutes = 3;
echo formattedTime($hours, $minutes); // 07:03

$hours = 10;
$minutes = 3;
echo formattedTime($hours, $minutes); // 10:03

$hours = 7;
$minutes = 30;
echo formattedTime($hours, $minutes); // 07:30

$hours = 10;
$minutes = 30;
echo formattedTime($hours, $minutes); // 10:30

?>

Example: https://rextester.com/HOPJR15721

zedfoxus
  • 35,121
  • 5
  • 64
  • 63