A Web Design Community curated by Chris Coyier

A little dab'll do ya

Code Snippets

Home » Code Snippets » PHP » Force Leading Zero Submit one!

Force Leading Zero

<?php
  function forceLeadingZero($int) {
    return (int)sprintf('%02d',$int);
  }
?>

Forces leading zero to integers.

was | now

1 | 01
2 | 02
3 | 03

10 | 10
100 | 100
99 | 99

Reference URL

Subscribe to The Thread

  1. LM says:

    str_pad?

  2. LM says:

    str_pad($input, 2, “0″, STR_PAD_LEFT);

  3. str_pad is probably more semantically accurate, but sprintf() is faster.

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