Generate 5-digit combinations

5

How do I generate combinations in 5-digit php ranging from 0 to 9?

In the same case, in the future you want to add letter, how should it be done?

    
asked by anonymous 02.08.2017 / 00:25

3 answers

7

You can put this code as follows:

    function gerarnumeros($length = 10) {
       return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length);
    }

* If you want to add letters, just put letters in the above code.

So you put gerarnumeros(5); in your code.

response based on this link

    
02.08.2017 / 00:32
4

One way to generate a combination of letters and numbers would be to use the shuffle function to mix the elements of an array and foreach by taking only the amount of characters passed as a parameter:

function gerarCombinacao($tam){
    // cria um vetor com os caracteres minúsculos, maiúsculos e números
    $seed = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
    // mistura os elementos do array
    shuffle($seed); 
    $rand = '';
    // pega somente a quantidade de caracteres passados 
    // na variável $tam como parâmetro
    foreach (array_rand($seed, $tam) as $k) $rand .= $seed[$k];    
    // retorna a combinação
    return $rand;
 }

To use, just pass the number of co-ordinations as a parameter:

 print gerarCombinacao(5);

See working on IDEONE .

    
02.08.2017 / 00:51
1

If it's just number could also use, no need to loop ( though personally believe the loop, used in the @ bfavaretto ♦ be better ):

echo sprintf('%05d', random_int(0, ((10 ** 5) - 1)));

Try this.

This would make it generate from 0 to 99999 , which is the maximum value that can be generated with 5 numbers.

If you want to increase the number you could change 5 for as long as you want, if you want to use some function a little more legible:

function gerar_numero($tamanho)
{
    return str_pad(random_int(0, str_repeat(9, $tamanho)), $tamanho, 0, STR_PAD_LEFT);
}
    
02.08.2017 / 04:57