samoht Posted June 16, 2009 Share Posted June 16, 2009 hello all, I have a simple for loop to populate a select box from 1 to 300 the only problem is the client wants the values to always have 3 digits - so 1 should be 001 and 2 should be 002 etc and 10 would be 010. I don't think number_format() will help me - What can I do? Thanks Link to comment https://forums.phpfreaks.com/topic/162378-solved-how-to-get-3-digits-in-a-for-loop/ Share on other sites More sharing options...
Garethp Posted June 16, 2009 Share Posted June 16, 2009 while (str_length($Value) < 3) { $Value = "0" . $Value; } or try str_pad Link to comment https://forums.phpfreaks.com/topic/162378-solved-how-to-get-3-digits-in-a-for-loop/#findComment-857063 Share on other sites More sharing options...
Mark Baker Posted June 16, 2009 Share Posted June 16, 2009 for ($i = 1001; $i <= 1300; $i++) { $id = substr($i,-3); } or for ($i = 1; $i <= 300; $i++) { $id = str_pad($i,3,'0',STR_PAD_LEFT); } Link to comment https://forums.phpfreaks.com/topic/162378-solved-how-to-get-3-digits-in-a-for-loop/#findComment-857065 Share on other sites More sharing options...
joel24 Posted June 16, 2009 Share Posted June 16, 2009 function ZeroFill($number) { if (strlen($number) == 1) { $number = "00".$number; } elseif (strlen($number) == 2) { $number = "0".$number; } return $number; } Link to comment https://forums.phpfreaks.com/topic/162378-solved-how-to-get-3-digits-in-a-for-loop/#findComment-857068 Share on other sites More sharing options...
MasterACE14 Posted June 16, 2009 Share Posted June 16, 2009 or just do... $number = (string)$number; Link to comment https://forums.phpfreaks.com/topic/162378-solved-how-to-get-3-digits-in-a-for-loop/#findComment-857069 Share on other sites More sharing options...
samoht Posted June 16, 2009 Author Share Posted June 16, 2009 Thanks for the replies! I'm not sure how to do the last suggestion but for ($i = 1; $i <= 300; $i++) { $id = str_pad($i,3,'0',STR_PAD_LEFT); } is quite simple. Thanks Link to comment https://forums.phpfreaks.com/topic/162378-solved-how-to-get-3-digits-in-a-for-loop/#findComment-857082 Share on other sites More sharing options...
MasterACE14 Posted June 16, 2009 Share Posted June 16, 2009 just do... for ($i = 1; $i <= 300; $i++) { $id = (string)$i; } Link to comment https://forums.phpfreaks.com/topic/162378-solved-how-to-get-3-digits-in-a-for-loop/#findComment-857090 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.