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 0010sprintf("%04s", -10);
returns 0-10
Where as:
sprintf("%04d", 10);
returns 0010sprintf("%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
Call to Undefined Function Oci_Connect, PHP_Oci8_12C.Dll, Windows 8.1, PHP5.6.6
Getting Elements of a Div from Another Page (Php)
Interview Question: How to Have an Echo Before Header
Php: What Is the Purpose of Session_Name
Php's Simplexml: How to Use Colons in Names
Dompdf - Attach Created PDF to Email
Program Cant Start Because PHP5.Dll Is Missing
Setlocale(Lc_All, 'En_Gb.Utf8') Not Working on Windows
JavaScript or Jquery Doesn't Work in Dynamically Generated Content
Moving from MySQL to MySQLi or Pdo
Key of Null Variable Equals Null Not Error
Attach Image to Facebook Event (PHP Sdk, Rest or Graph API)
Adding User Custom Field Value to Order Items Details
How to Implement a Read-Only Member Variable in PHP