PHP: Prepend leading zero before single digit number

It will only add the zero if it's less than the required number of characters.

When working with numbers, you should use %d (rather than %s), especially when there is the potential for negative numbers. If you're only using positive numbers, either option works fine.

For example:

sprintf("%04s", 10); returns 1000
sprintf("%04s", -10); returns 0-10

Where as:

sprintf("%04d", 10); returns 1000
sprintf("%04d", -10); returns 100

<?php
    $num = 4;
    $num_padded = sprintf("%02d", $num);
    echo $num_padded; // returns 04
?>
You can use sprintf: http://php.net/manual/en/function.sprintf.php.

Comments

Popular posts from this blog

PHP: Date Difference for PHP 5.2

HTML5 video loop src change on end play function

Custom OpenCart 2.3.0.2 theme