PHP prepend leading zero before single digit number, on-the-fly

PhpStringNumbersZero

Php Problem Overview


PHP - Is there a quick, on-the-fly method to test for a single character string, then prepend a leading zero?

Example:

$year = 11;
$month = 4;

$stamp = $year.add_single_zero_if_needed($month);  // Imaginary function

echo $stamp; // 1104

Php Solutions


Solution 1 - Php

You can use sprintf: http://php.net/manual/en/function.sprintf.php

<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>

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

Edit: As pointed out by @FelipeAls:

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 0010
sprintf("%04s", -10); returns 0-10

Where as:

sprintf("%04d", 10); returns 0010
sprintf("%04d", -10); returns -010

Solution 2 - Php

You can use str_pad for adding 0's

str_pad($month, 2, '0', STR_PAD_LEFT); 

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

Solution 3 - Php

The universal tool for string formatting, sprintf:

$stamp = sprintf('%s%02s', $year, $month);

http://php.net/manual/en/function.sprintf.php

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBenView Question on Stackoverflow
Solution 1 - PhpKirk BeardView Answer on Stackoverflow
Solution 2 - PhpGauravView Answer on Stackoverflow
Solution 3 - PhpdecezeView Answer on Stackoverflow