Web Development for 2012

Alexander Dickson - Web Developer covering PHP, jQuery / Javascript, XHTML, CSS, more

Formatting a number with leading zeroes in PHP

Published on Tuesday, 16th March 2010.

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

Comment Details

Your email will never be displayed. If you have a gravatar, it will be displayed.

Note: Your comment may require approval before it is posted to the site.

Stack Overflow Profile

view full profile »

About

I'm a web developer from the Sunshine Coast, Australia. more »