Robert E Robert E - 1 year ago 71
PHP Question

Use PHP to echo 05 instead of just 5 as example. How do I do this?

I am using a bit of PHP right now to output how many days, hours, minutes and seconds are left until a specific date. It works great, but as of right now, it will output something like: 14:5:33:36

Ideally, if it's less than 10 I'd like it to output 05 instead of just 5. I know this must be fairly simple in PHP, but being a front end developer... I just can't quite wrap my brain around this. Below is the code I'm currently using:

$rem = strtotime('2013-02-01 14:00:00') - time();
$day = floor($rem / 86400);
$hr = floor(($rem % 86400) / 3600);
$min = floor(($rem % 3600) / 60);
$sec = ($rem % 60);
echo "$day:";
echo "$hr:";
echo "$min:";
echo "$sec";

How can this be accomplished?

Answer Source

You can use str_pad with the STR_PAD_LEFT flag.

$num = 5;
echo str_pad($num, 2, "0", STR_PAD_LEFT);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download