Complete number with leading zeros with PHP

5

I have a field with a limit of 4 characters where I will enter a value, I would like the remaining space to be completed with zeros from left to right, for example, if the user enters the number 4. I would have to leave 0004 if I inserted 100 , would have to quit 0100, if 1000 was inserted, would quit 1000, and so on.

How can I do this with PHP?

    
asked by anonymous 26.10.2017 / 18:14

2 answers

8

Use the str_pad function in conjunction with the STR_PAD_LEFT flag.

echo str_pad('5' , 4 , '0' , STR_PAD_LEFT);

Output:

  

0005

Or with 100:

echo str_pad('100' , 4 , '0' , STR_PAD_LEFT);

Output:

  

0100

    
26.10.2017 / 18:18
4

Use str_pad() function to add the leading zeros and pass the fourth argument as STR_PAD_LEFT .

echo str_pad(1, 4, 0, STR_PAD_LEFT);
echo str_pad(10, 4, 0, STR_PAD_LEFT);
echo str_pad(100, 4, 0, STR_PAD_LEFT);
echo str_pad(1000, 4, 0, STR_PAD_LEFT);

Output:

0001
0010
0100
1000

Related:

Use CONCAT to adjust the number of php mysql numbers

    
26.10.2017 / 18:18