PHP – Is there a quick, on-the-fly method to test for a single character string, then prepend a leading zero?
Example:
$year = 11;
$month = 4;
$stamp = $year.add_single_zero_if_needed($month); // Imaginary function
echo $stamp; // 1104
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use sprintf: http://php.net/manual/en/function.sprintf.php
It will only add the zero if it’s less than the required number of characters.
Edit: As pointed out by @FelipeAls:
When working with numbers, you should use
%d(rather than%s), especially when there is the potential for negative numbers. If you’re only using positive numbers, either option works fine.For example:
sprintf("%04s", 10);returns 0010sprintf("%04s", -10);returns 0-10Where as:
sprintf("%04d", 10);returns 0010sprintf("%04d", -10);returns -010