Formatting a number with leading zeroes in PHP
Way back, when I was more of a novice, I wrote a function in PHP that padded numbers with leading zeroes. You can take a wild guess at how I implemented it too. If you guessed things like if ($num < 9) then you'd be right. It was awful. I'm sure now there is a much better way.
Whilst learning C, I realised that PHP had its own implementation of the printf() function. I'm going to use the sprintf() version however, that returns the value instead of automatically echoing it. I'm sure these 2 PHP functions are just light wrappers around C's printf().
function leadingZeroes($number, $paddingPlaces = 3) {
return sprintf('%0' . $paddingPlaces . 'd', $number);
}Just give it a number, and an optional padding amount and enjoy!
Also, if you owned a Nintendo 64 and loved GoldenEye 007 and Perfect Dark, and now own an Xbox 360, this will be the most exciting news you'll get for a while: Perfect Dark for Xbox 360 Live Arcade is being released tomorrow!
Comments
L3gend
Posted on Saturday, 20th March 2010 @ 2:55pm.you suck and golden eye, prefect dark
Leave a Comment
Note: Your comment may require approval before it is posted to the site.