Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What does it mean to add leading zeros?

This means that when you make 1 as 001, Excel treats the new result as text with three characters (just like abc or xyz). Here is how to add leading zeroes using the TEXT function: If you have the numbers in column A (say from A2:A100), then select B2:B100 and enter the following formula: =TEXT(A2,”00000″)


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


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


The universal tool for string formatting, sprintf:

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

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