How can you create a random hexadecimal number, say 5 digits? That is to say something like: A31D4.
Doing the following:
$mirand = dechex(rand());
It generates random numbers for me but sometimes they are 3 digits and most of the time they are 4, never 5.
I have always liked this solution, it may use a not so orthodox method, but it has worked for me, it is simple and short:
You can enter a range of values in
rand()
if you wish.I have created the following function, which receives as a parameter the number of digits that the hexadecimal code must have.
For an even number of characters, something short:
For the most general case, you would have to write some more code.
Edited :
...and the general case:
With Php7 I would do it like this:
Since Php has a native function to convert a decimal to hexadecimal ( link documentation ), you simply get a random decimal and convert it to hexadecimal.
If you want n values, you call the function inside a loop:
But it's up to you how to use the function. It can still be like this:
And finally, the :string is a new feature of Php7 with which you indicate the type of return value, in this case string because it can return letters and numbers.
Greetings.