Pad a number with leading zeros in PHP

August 19th, 2010 by paul Leave a reply »

Just a quick one to share a couple of ways to pad a number with leading zeros… I’ve seen a lot of really poor examples of how to do this so I thought I’d share the two ways I might add leading zeros to a number in PHP.

function number_pad($n, $pad_len) {
     return sprintf("%0{$pad_len}d", $n);
}
function number_pad($n, $len) {
     return str_pad($n, $len, '0', STR_PAD_LEFT);
}
Advertisement

Leave a Reply