php random x digit number

前端 未结 21 2185
耶瑟儿~
耶瑟儿~ 2020-12-04 15:00

I need to create a random number with x amount of digits.

So lets say x is 5, I need a number to be eg. 35562 If x is 3, then it would throw back something like; 463

21条回答
  •  悲哀的现实
    2020-12-04 15:45

    Here is a simple solution without any loops or any hassle which will allow you to create random string with characters, numbers or even with special symbols.

    $randomNum = substr(str_shuffle("0123456789"), 0, $x);

    where $x can be number of digits

    Eg. substr(str_shuffle("0123456789"), 0, 5);

    Results after a couple of executions

    98450
    79324
    23017
    04317
    26479
    

    You can use the same code to generate random string also, like this

    $randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTVWXYZ"), 0, $x);
    

    Results with $x = 11

    FgHmqpTR3Ox
    O9BsNgcPJDb
    1v8Aw5b6H7f
    haH40dmAxZf
    0EpvHL5lTKr
    

提交回复
热议问题