How to Keep Leading Zeros in PHP Integer

How to keep leading zeros in PHP integer

You cannot keep leading zeros in integer. You can either keep them in a string or add at output time, using sprintf(), str_pad(), etc.

Adding numbers with leading zeros

With str_pad:

For($i=1; $i<=44; $i++){
Echo str_pad($i,5,"0",STR_PAD_LEFT) ."\n";
}

https://3v4l.org/Pe3M2

Str_pad(start number, length of string you want, what type of padding, where to place the padding [left/right])

Formatting a number with leading zeros in PHP

Use sprintf :

sprintf('%08d', 1234567);

Alternatively you can also use str_pad:

str_pad($value, 8, '0', STR_PAD_LEFT);

How to increment a value with leading zeroes using php

use str_pad()

$val = 1;
echo str_pad($val,4,"0",STR_PAD_LEFT); // 0001

$val = 10;
echo str_pad($val,4,"0",STR_PAD_LEFT); // 0010

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

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

PHP - Add leading zeros to number but keep maximum length

Use str_pad function of PHP

$input = 1;
$number = str_pad($input, 7, "0", STR_PAD_LEFT);


Related Topics



Leave a reply



Submit