Reputation: 9
I need a way to be able to automatically add a '0' in front of any number if the number a user enters is a number between 1-9 in PHP. I need this because I am trying to make a 10 character date so that I can search for exercises added to my website between the dates.
The easiest way to do this I thought was to start with a year, then the month, then the day so I get something like this: 2001/04/15. I can just have the user manually add a '0', but I was hoping there was a way to do that automatically.
So far, I have this, but it doesn't work quite right. Can someone help me out here?
Thanks in advance.
//Checks to see if start day is a number 1-9
//If so, adds a '0' at the beginning of the start day variable
if($_POST['eday'] == 1 || $_POST['eday'] == 2 || $_POST['eday'] == 3 || $_POST['eday'] == 4 ||
$_POST['eday'] == 5 || $_POST['eday'] == 6 || $_POST['eday'] == 7 || $_POST['eday'] == 8 ||
$_POST['eday'] == 9) {
$_POST['eday'] = 0 . $_POST['eday'];
echo $_POST['eday'] . '<br>';
}
Upvotes: 0
Views: 61
Reputation: 10682
Here is another thing: http://www.w3schools.com/php/func_string_str_pad.asp
pad_str($str,20,".");
will pad out to 20 characters of "."
There is and optional 4th parameter.
STR_PAD_BOTH
STR_PAD_RIGHT (Default if not supplied)
STR_PAD_LEFT
so for you:
$str = $_POST['eday'];
pad_str($str,2,"0", STR_PAD_LEFT);
Now $str
is set and you can use it where ever you need.
Upvotes: 0
Reputation: 365
You are complicating yourself for nothing dude, you could do it like that :
if($_POST['eday'] < 10) $number = '0'.$_POST['eday'];
else $number = $_POST['eday'];
Upvotes: 0