简体   繁体   中英

How to generate a 9 digit number

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.

eg 102-394-458

I'm also debating whether

  • to store it as a number or do the formatting on the front end
  • or to store it as a number and do the formatting on the backend
  • or to just store the dashes in the database as well

Of course the choice will affect how the number is generated.

implode('-',str_split(rand(100000000,999999999),3))

通常,最好只是将其存储为数字,并将其格式化 - 仅用于显示目的

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,"","-");

生成1到9之间的随机数。在0到9之间生成8个随机数。将它们组合成一个字符串,在需要的位置添加短划线。

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM