Zero fill a number using PHP

Have you ever needed to make sure your number is a certain length for output? Say you have the number 6 but need to make sure it is 4 digits and out put like: 0006. How would you go about this? One way to do this is the following:

<?php
function zerofill ($num,$zerofill) {
while (strlen($num)<$zerofill) {
$num = "0".$num;
}
return $num;
}

?>

The usage of this code would be:

<?php echo zerofill(6, 7); ?>

Output will be 00006

Keep Enjoying..

You can leave a response, or trackback from your own site.

2 Responses to “Zero fill a number using PHP”

  1. Siva Senthil Ram says:

    Gud stuff… i am expecting more from u… keep posting

  2. Raul says:

    Have you tried using str_pad function?

    function zerofill ($number,$length) {
    return str_pad($number,$length,”0″,STR_PAD_LEFT);
    }

    Example:

    In this case output will be 0007.

    Regards

Leave a Reply