Generate 5 digit combinations

Asked

Viewed 1,170 times

5

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

In that same, in the future want to add letter, as it should be done?

3 answers

7


You can put this code the following:

    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 code above.

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

reply based on this link

  • Thank you. What would that be 10 in the ($length = 10)

  • @James no, it would be as he put in the same example. gerarnumeros(5) to generate combinations with 5 digits. If you want with 7 digits, put gerarnumeros(7)

  • @acklay I understand, but I’d like to know what it’s about ($length = 10)

  • 2

    @James this means that if you do not put a size, leave the function without parameter, it will take the assigned value as default. Take the test using only: gerarnumeros()

4

A way to generate a combination with letters and numbers, would be using the function shuffle to mix the elements of a array and the foreach taking only the amount of characters passed as 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 as parameter the amount of shells:

 print gerarCombinacao(5);

Behold working at IDEONE.

1

If it is only number could also use, no need for loop (although personally believe that the loop, used in the response of @bfavaretto be better):

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

Test this.

That would generate from 0 until 99999, which is the maximum value that can be generated with 5 numbers.

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

function gerar_numero($tamanho)
{
    return str_pad(random_int(0, str_repeat(9, $tamanho)), $tamanho, 0, STR_PAD_LEFT);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.