Zero Padded Numbers

function getZeroPaddedNumber($value, $padding) {
       return str_pad($value, $padding, "0", STR_PAD_LEFT);


echo getZeroPaddedNumber(123, 4);
// outputs "0123"


  1. User Avatar
    Permalink to comment#

    I don’t really know why this could be useful. I appreciate the effort of you posting snippets but here me out on this one:

    Using this function:
    echo getZeroPaddedNumber(123, 4);
    Will “cost” me 35 characters.

    Using this:
    str_pad(123, 4, “0”, STR_PAD_LEFT);
    Will “cost” me 39 characters.

    So using this custom function will cost me more space (and time?) then using the built-in function. If the argument is that with this function you won’t have to remember “STR_PAD_LEFT” then maybe you should consider training your memory or finding another job (if webdev is your job now ;))

    Don’t get me wrong. I could sound a bit harsh, but it’s just a users point of view. No personal offense.

    • User Avatar
      Permalink to comment#

      Small correction there.

      It should be like this:

      Using this:
      echo str_pad(123, 4, “0″, STR_PAD_LEFT);
      Will “cost” me 48 characters.


      Both functions need an echo ;-)

  2. User Avatar
    Permalink to comment#

    This is just rewriting an existing function. There’s no point to it.

  3. User Avatar
    Ramesh Chowdarapally
    Permalink to comment#

    In simple steps you have given useful code.

  4. User Avatar
    Felix Riesterer
    Permalink to comment#

    sprintf('%04d', 123);

    21 characters and no custom function needed.

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.