Zero fill a number
By: Daniel

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

<?php
function zerofill ($num,$zerofill) {
    // Get the current string length of the original number
    // Loop through that number until it has reached the count in $zerofill
    while (strlen($num)<$zerofill) {
        $num = "0".$num;
    }
    return $num;
}
?>

The usage of this code would be:

<?php
// Output will be 005
echo zerofill(5, 3);
?>

Enjoy!

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 1.00 out of 5)
Loading ... Loading ...

9 Responses to “Zero fill a number”

  1. irvin Says:

    Nice! I’m looking for something like that..

  2. Hasan Ozgan Says:

    it’s like echo sprintf(“s”, 5);

  3. sLn Says:

    Did You know that there is a php function str_pad
    It does the same, and even more
    check it ;)

  4. 15 Top PHP Coding Tutorials, Tips and Tricks | Web Design Tutorials | Creating a Website | Learn Adobe Flash, Photoshop and Dreamweaver Says:

    [...] Learn how to make a number a certain amount of characters. Such as 5 you could make to 005. http://www.wlscripting.com/tutorial/55 [...]

  5. Burak Erdem Says:

    As sLn said, there is a built-in function, named str_pad.

    Btw, I advice you to upgrade your Wordpress to the latest stable version to prevent hacks and attacks.

  6. 15 Very Useful PHP Tutorials Says:

    [...] 15. Zero fill a number [...]

  7. Craig van der Merwe Says:

    Now show us how to do a php zero fill bitwise operation (ie. like the >>> operator in JavaScript).

    Points to sLn

  8. w13531 Says:

    http://php.net/manual/de/function.sprintf.php

    string sprintf ( string $format [, mixed $args [, mixed $... ]] )

    wold be better than a loop

  9. 15 Very Useful PHP Tutorials | The Apple Tech Blog Says:

    [...] 15. Zero fill a number [...]

Leave a Reply

geovisitors