How to set and manipulate the number of digits in an integer type variable with php?

Asked

Viewed 41 times

2

Good morning!

I am building a system with php/sql that works with letters which in a certain part need to generate a 6-digit sequential code that will be for each letter to be sent.

letter 1 must have the code "000001", letter 2: "000002", letter 3: "000003", and so on.

I have saved in sql only the last numbers like 1,2 and 3. How do I add the other 0’s to the left limiting to the maximum number of 6 digits? Putting 5 0’s as 000001 or even 3 as 000143 if applicable.

1 answer

3


You can use the PHP str_pad function as follows:

$nomeDaVariavel = 1;

$nomeDaVariavel = str_pad($nomeDaVariavel, 6, "0", STR_PAD_LEFT);

// Irá printar 000001 como texto
print $nomeDaVariavel;

The first parameter is the text to be treated, the second is the final quantity that should have the text, the third is the character that will be inserted and the fourth parameter is where the insertion will take place.

Your database will need to be updated to the text type field for this column, since 000001 is not an integer, because of the zeroes on the left. Or, you will have to perform the treatment on all the points that need to be displayed the zero on the left.

Browser other questions tagged

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