Formatting a Number With Leading Zeros in PHP

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

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

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

Adding leading 0 in php

If it is coming from a DB, this is the way to do it on a sql query:

lpad(yourfield, (select length(max(yourfield)) FROM yourtable),'0') yourfield

This is will get the max value in the table and place the leading zeros.

If it's hardcoded (PHP), use str_pad()

str_pad($yourvar, $numberofzeros, "0", STR_PAD_LEFT);

This is a small example of what I did on a online php compiler, and it works...

$string = "Tutorial 1 how to";

$number = explode(" ", $string); //Divides the string in a array
$number = $number[1]; //The number is in the position 1 in the array, so this will be number variable

$str = ""; //The final number
if($number<10) $str .= "0"; //If the number is below 10, it will add a leading zero
$str .= $number; //Then, add the number

$string = str_replace($number, $str, $string); //Then, replace the old number with the new one on the string

echo $string;

Adding leading zeros to number_format

You'll need to get rid of the commas first:

$number = str_replace( ',', '', $number );

Then you can use str_pad as was suggested in this question, which Francesco Malatesta posted as a comment.

$number = str_pad( $number, 3, '0', STR_PAD_LEFT );

You can reduce it to a oneliner:

$number = str_pad( str_replace( ',', '', $number ), 3, '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


Related Topics



Leave a reply



Submit