Change language

Format number with leading zeros in PHP

|
Examples :
Input: 1234567 Output: 01234567 Input: 1234 Output: 00001234 
There are many ways to pad leading zeros in string format. But in the case of a string, the best way to solve the problem is - use the function sprintf, and also use the function substr() .
  • function sprintf()
  • substr() functin
Using sprintf():sprintf() is used to return a formatted string. 
Syntax:
sprintf (format, $variable) // Returns the variable formated according to the format provided. 
  • Example 1:This example uses the sprintf() function to display a number with leading zeros. $var = 1234567; echo sprintf ( ’% 08d’ , $var ); ?> Output:
    01234567 
  • Example 2: Inthis example uses the sprintf() function to display negative numbers with leading zeros. $var1 = -10; $var2 = 10; echo sprintf ( ’% 04s’ , $var1 ). "" ; echo sprintf ( ’% 04s’ , $var2 ); ?> Output:
    0-10 0010 
    In the above example, we tried to format the number as a string and messed up the negative. But this will not happen if we format the numbers using "% d" rather than "% s".
  • Example 3: $var1 = -10; $var2 = 10; echo sprintf ( ’% 04d’ , $var1 ). "" ; echo sprintf ( ’% 04d’ , $var2 ); ?> Output:
    -010 0010 
Using substr() Function:This function is used to return a portion of a string. 
Syntax:
substr (string $string, int $start, int $length) // Returns the portion of string that define at start and length of the parameter ... 
Example : $num = 123; $str_length = 4;  
// Left padding if number < $str_length $str = substr ( "0000 {$num}" , - $str_length ); echo sprintf ( $str ); ?>
Output:
0123 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method