View Full Version : Convert number to 2 digits

04-04-2007, 04:40 PM
hi guys,

I have a variable $day_num which contains the day of the month, but if its 1-9 it only displays as "1" or "9", I'm looking to convert the variable to display as 2 digits, ie. "01", or "09", etc. any ideas?

Here's my code:

//sets the first day of the month to 1
$day_num = 1;

//count up the days, untill we've done all of them in the month

( $day_num <= $days_in_month )

echo "<td>$day_num<br><input name=\"$day_num$month$year\" type=\"checkbox\" value=\"yes\"></td>\n";

04-04-2007, 04:50 PM

04-04-2007, 04:54 PM
Edit: Too late, basically says the same as above ^^

Of the dozen ways you could do this, the str_pad(...) function is one way - http://php.net/str_pad

04-04-2007, 05:08 PM
I'm only a bit of a newbie editing someone elses code so how would i go about doing that in this example?

04-04-2007, 05:16 PM
At least give it a go and post what you come up with. If you dont try, you'll never learn.

04-04-2007, 05:17 PM
It's not that hard. You know the variable that needs changing, so look at the examples given on the page shown.

str_pad ($input, $pad_length, $pad_string, $pad_type)

You know what $input is as you mentioned what the variable name is in your original post.
You know the length, as you want 2 numbers showing.
You know what you want to pad the variable with, as you mentioned you wanted 0's
And the direction of the pad is from the left.

str_pad ($day_num, 2, "0", STR_PAD_LEFT)

So put that where $day_num is in your code

04-04-2007, 05:22 PM
I wrote a function for exactly the same thing, hope it helps:

function dotwodigits($val) {
if (intval($val) < 10) {
$twodigits = "0$val";
elseif (intval($val) >= 10) {
$twodigits = $val;
return $twodigits;