Vivid Lust Posted August 27, 2009 Share Posted August 27, 2009 Any idea how to put a 0 in front of single digit numbers, any formatting out there? Thanks. Link to comment https://forums.phpfreaks.com/topic/172165-number-form-8-08/ Share on other sites More sharing options...
KevinM1 Posted August 27, 2009 Share Posted August 27, 2009 Any idea how to put a 0 in front of single digit numbers, any formatting out there? Thanks. Have you tried simply: $num = 8; echo "0" . $num; ? Link to comment https://forums.phpfreaks.com/topic/172165-number-form-8-08/#findComment-907756 Share on other sites More sharing options...
Vivid Lust Posted August 27, 2009 Author Share Posted August 27, 2009 If I'm looping through numbers 1 to 50 Link to comment https://forums.phpfreaks.com/topic/172165-number-form-8-08/#findComment-907757 Share on other sites More sharing options...
Maq Posted August 27, 2009 Share Posted August 27, 2009 Check out: str_pad. Link to comment https://forums.phpfreaks.com/topic/172165-number-form-8-08/#findComment-907759 Share on other sites More sharing options...
lemmin Posted August 27, 2009 Share Posted August 27, 2009 I think it is as simple as what Nightslyr said. You can simply check the length of the string if you are doing multiple digit numbers as well: function leadingZero($num) { if (strlen($num) == 1) return "0" . $num; } Link to comment https://forums.phpfreaks.com/topic/172165-number-form-8-08/#findComment-907760 Share on other sites More sharing options...
Maq Posted August 27, 2009 Share Posted August 27, 2009 $s = 8; echo (strlen($s)==1) ? str_pad($s, 2, "0", STR_PAD_LEFT) : $s; ?> Or, as Nightslyr suggested: $s = 8; echo (strlen($s)==1) ? "0" . $s : $s; ?> Link to comment https://forums.phpfreaks.com/topic/172165-number-form-8-08/#findComment-907762 Share on other sites More sharing options...
akitchin Posted August 27, 2009 Share Posted August 27, 2009 <?php $s = 8; echo (strlen($s)==1) ? str_pad($s, 2, "0", STR_PAD_LEFT) : $s; ?> note that when using str_pad(), you don't even need to check the string's length. no padding will be performed if the input string is equal to or greater than the pad length. Link to comment https://forums.phpfreaks.com/topic/172165-number-form-8-08/#findComment-907773 Share on other sites More sharing options...
Maq Posted August 27, 2009 Share Posted August 27, 2009 $s = 8; echo (strlen($s)==1) ? str_pad($s, 2, "0", STR_PAD_LEFT) : $s; ?> note that when using str_pad(), you don't even need to check the string's length. no padding will be performed if the input string is equal to or greater than the pad length. Ah, yeah sorry about that. Thanks. $s = 8; echo str_pad($s, 2, "0", STR_PAD_LEFT); Link to comment https://forums.phpfreaks.com/topic/172165-number-form-8-08/#findComment-907803 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.