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
CodePudding user response:
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