CSS-Tricks*

A Web Design Community curated by Chris Coyier

A little dab'll do ya

Code Snippets

Code Snippets > PHP > Zero Padded Numbers Submit one!

Zero Padded Numbers

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

Usage

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

Subscribe to The Thread

  1. Robin says:

    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 says:

      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 says:

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

It's Your Turn

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
--- The Management ---