The Lodge is members-only design/dev videos and Office Hours.

Next Office Hours Session: "Programming Fundamentals" Dec 02 - 2:00 PM Eastern

Zero Padded Numbers

Last updated on:
function getZeroPaddedNumber($value, $padding) {
       return str_pad($value, $padding, "0", STR_PAD_LEFT);


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


  1. Robin
    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.

    • Robin
      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. Ben
    Permalink to comment#

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

  3. Ramesh Chowdarapally
    Permalink to comment#

    In simple steps you have given useful code.

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed