Complete number with zeros on the left with PHP

Asked

Viewed 12,279 times

5

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

How can I do this with PHP?

  • Do you want these zeroes to appear when the user enters a value? If so, you will need to do it with Javascript.

  • It is not necessary, it is enough that the output goes out that way

2 answers

17


Use the function str_pad together with the flag STR_PAD_LEFT.

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

Exit:

0005

Or with 100:

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

Exit:

0100

  • If I have a variable: $number = 30; Just do it this way? echo str_pad( $number , 4 , '0' , STR_PAD_LEFT); ?

  • 2

    @Feliperodrigues exactly that, just add to the first parameter.

4

Use function str_pad() to add the zeros to the left 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);

Exit:

0001
0010
0100
1000

Related:

Use CONCAT to adjust the amount of php mysql numbers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.