AdRock Posted April 14, 2009 Share Posted April 14, 2009 Just come across a problem i need to fix. I connect to database and count the number of rows which could be 2 or more. I need to create numbers based on the row count so if there is 15 rows in the database, i need my variable to be 015 or if there is only 2 rows i need 002. I can get the row count and apply it to a variable but how do i add leading zeros so my variable is always 3 digits long? Link to comment https://forums.phpfreaks.com/topic/154117-solved-integers-with-leading-zeros/ Share on other sites More sharing options...
Mchl Posted April 14, 2009 Share Posted April 14, 2009 sprintf (see examples) Link to comment https://forums.phpfreaks.com/topic/154117-solved-integers-with-leading-zeros/#findComment-810148 Share on other sites More sharing options...
jackpf Posted April 14, 2009 Share Posted April 14, 2009 $number = 1; $number = preg_split('/[0-9]/', $number); for($i = 0; $i < 3; $i++) { if(!isset($number[$i])) { $preceding_zeros += 1; } } $number = (0 * $preceding_zeros) + implode($number); Something like that? Link to comment https://forums.phpfreaks.com/topic/154117-solved-integers-with-leading-zeros/#findComment-810149 Share on other sites More sharing options...
jackpf Posted April 14, 2009 Share Posted April 14, 2009 Oh. Didn't know there was already a function for this. Tis usually the case Link to comment https://forums.phpfreaks.com/topic/154117-solved-integers-with-leading-zeros/#findComment-810151 Share on other sites More sharing options...
PFMaBiSmAd Posted April 14, 2009 Share Posted April 14, 2009 str_pad would also work. Link to comment https://forums.phpfreaks.com/topic/154117-solved-integers-with-leading-zeros/#findComment-810158 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.