Pad a number with leading zeros in PHP

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.

<?php
function number_pad($n, $pad_len) {
     return sprintf("%0{$pad_len}d", $n);
}

function number_pad_alt($n, $len) {
     return str_pad($n, $len, '0', STR_PAD_LEFT);
}
comments powered by Disqus