Can someone show me how to do the following?
I have a variable named $day. If the value of $day is between 1 and 9 and it is represented by a single digit like “1”, I would like to set $day to 01.
How would I do this?

Recommended Answers

All 3 Replies

<?php
$day = "2";
$newday = printf("%02s", $day); 
echo $newday;
?>

Result is 02.

<?php
$day = "2";
$newday = printf("%02s", $day); 
echo $newday;
?>

Result is 02.

Thanks!
I also found this after a bit more searching:

if($day < 10) {
     $day = str_pad($day, 2, '0', STR_PAD_LEFT);
}

if statement is redundant
str_pad does nothing if the string is equal to or longer than the pad_length

$day = str_pad($day, 2, '0', STR_PAD_LEFT);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.