Reputation: 119
I'm trying to use php to generate a 9 digit number that does not start with a 0 and is separated by dash every third number.
e.g. 102-394-458
I'm also debating whether
Of course the choice will affect how the number is generated.
Upvotes: 3
Views: 8646
Reputation: 340191
Use number_format() on the frontend. Storing it formatted will mean you will have to "deformat" it if you want to perform any operation with it that requires it being a number.
The way to generate such a number is:
$number = mt_rand(100000000,999999999);
You can use number_format like this:
echo number_format($number,0,"","-");
Upvotes: 6
Reputation: 212412
implode('-',str_split(rand(100000000,999999999),3))
Generally, it's probably better simply to store as a number, and format it with the - only for display purposes
Upvotes: 18
Reputation: 101926
You should save as an unsigned integer in your database and format on display (but still on server-side, if this is what you mean by backend.)
To generate the number use
mt_rand(100000000, 999999999);
To display use:
wordwrap($number, 3, '-', true);
Upvotes: 4
Reputation: 20721
Generate a random number between 1 and 9. Generate 8 random numbers between 0 and 9. Combine them into a string, adding dashes where desired.
Upvotes: 3