• 0

[PHP] How to generate unique random number?


Question

Hi,

I wanted to generate at least one thousand of unique 16-digit number using Random Number Function.

Like

1010101010000001

1234501010009801

9087651340298745

4390192836456106

I don't want the negative number. And I want the number to be exact 16-digit, for example, it should be 000000000002323, not 2323

I have scripted the code

echo "<table width=\"100\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
for ($i=0;$i<1000;$i++)
	{
echo "<tr><td>";
echo rand(0000000000000000,9999999999999999);
echo "</td></tr>";
	}
echo "</table>";

But I am not too sure on how to generate one thousand unqiue of 16-digit number using PHP code. Anyone of you who can help with this?

Thanks alot. :D

Oops! I realised that I posted in wrong section. Can any moderator please help moving this to correct section?

Thanks :blush:

Edited by Novawin

9 answers to this question

Recommended Posts

  • 0

The only way you can guarantee that the numbers you're generating will be unique is to store all of them in to an array, and then compare the newly generated random number against that array. If the number exists already, ignore it and generate another one, if it doesn't, add it to the array and then start again.

  • 0
<?php
$max = 1000;
$digits = 16;

$numbers = array();
$power = pow(10, $digits);

for($i=0;$i<$max;$i++)
{

	$num = str_pad(mt_rand(0, $power), $digits, "0", STR_PAD_LEFT);
	if (!in_array($num, $numbers))
		$numbers[] = $num;
	else
		$i--;
}

print_r($numbers);
?>

  • 0

Thanks all for your reply.

By the way, I tried to use array() inside PHP code as shown below

<?php

function number($length)
{
   $array = array();
   for($i=0;$i<$length;$i++)
	 $key .= rand(0,9);

   return $key;
}

echo "<table width=\"100\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
for ($i=0;$i<1000;$i++)
  {
  echo "<tr><td>";
  echo number(16);
  echo "</td></tr>";
  }
echo "</table>";

?>

This has met my requirement but some number are repeated. I want every number to be unique and it can't be repeated. Can anyone of you please help checking my code and try to modify as possible to only display every unique number?

Thanks alot! :D

Edited by Novawin
  • 0

Never mind about this. I found out that after I uploaded the webpage to Linux Server, all 16-digit number are unique whereas this webpage being tested on localhost on my Windows laptop, some numbers are repeated. This is so weird... But it's okie anyway. Thanks all for your help. :cool:

  • 0

it repeates due to it taking some information from the system clock IIRC. dont quote me on that but i think it takes one number from the system, which is sometimes repeated.

i think its something like that, and no matter what you do unless like stated you create an array then there is no way 2 generate a unique number everytime

  • 0

I am new to programming. Please I need help. I want to use the above codes for my project but I only need 12 digits. When I change the digits =12, the code generated the following error ; Warning: mt_rand(): max(-727379968) is smaller than min(0) in C:\xampp\htdocs\ITB\RECOS\Theme\random.php on line 11

I do not have any idea of what that means.

Thanks in advance.

  • 0
  On 24/08/2015 at 12:21, Osy Odife said:

I am new to programming. Please I need help. I want to use the above codes for my project but I only need 12 digits. When I change the digits =12, the code generated the following error ; Warning: mt_rand(): max(-727379968) is smaller than min(0) in C:\xampp\htdocs\ITB\RECOS\Theme\random.php on line 11

I do not have any idea of what that means.

Thanks in advance.

<?php
$max = 10;

$digits = 12;


$numbers = array();

$power = pow(10, $digits);


for($i=0;$i<$max;$i++){
 $num = str_pad(rand(0, $power), $digits, "0", STR_PAD_LEFT);
 if(!in_array($num, $numbers)){
  $numbers[] = $num;
 }else{
  $i--;
 }
}


print_r($numbers);

?>

Here's the code corrected code for 12 digits, the problem was with the mt_rand function, it only works with 2, 4, 8, 16, 32, 64 etc digits.

Welcome to neowin :D

 

Edit: something doesn't seem to work correctly, rewriting the code.

Edited by Seahorsepip
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I know I will get shot down for this, but I prefer Windows 8, take the start screen away and use a third party start menu and Windows 8 was a pretty good OS for Microsoft. It was stable and ran very smoothly on my AMD bulldozer based computer, Windows 10 ran like a dog. When I changed to a Ryzen 7 17090 CPU, I tried to keep Windows 8 on it, but MS made that difficult with pop-ups all the time to get me to change to Windows 10 and the hacks to stop it, did not work that well. I have seen for a few years now the way Windows is going, and I don't like it and with Windows 11, what I saw was happening with Windows 10 have got worse with 11, certainly now with this AI rubbish. When I was looking at updating my PC a couple of years ago, I was looking at what CPUs were available, price and if it was going to make a lot of difference to what I use the machine for. To update my Pc to would have cost me £700 or more, that is just for the CPU, memory and board, maybe get a new case, the GPU is fine for what I use it for. I waited to see what AMD was bringing out and I thought I would look at what Apple was doing with their machines, and they launched the M2 machine at around the same time as AMD launched a new gen version of their Ryzen chip. A Mac mini m2 pro was £1,300, I had saved the money up over 12 months and yes the mini was over £600 more than the parts to update the PC, but it was a complete computer. I had the money, so I thought stick it, let's go for it. I don't regret it, what I do regret is not going for Mac years ago. Saying that Apple used Intel chips and I hate intel. I will have to update the PC at some point, but I will go for a R5 and not R7 and have less memory and a cheaper motherboard as the machine is only used for a few games these days.
    • Gemini CLI brings AI smarts to your Firebase terminal experience by Paul Hill Google has added its Gemini AI model directly into the command-line interface of Firebase Studio, its cloud-based IDE that uses AI to help with projects. The Gemini Command Line Interface (CLI) means that developers can expand past using AI for code, they can now also use AI for content generation and research without leaving the IDE. Gemini CLI comes with free usage tiers (60 model requests per minute, 1,000 requests per day with a Google login), it offers advanced AI features, and includes integrated Google Search for real-time content. Gemini CLI is also open source so it can be customized and accepts contributions. Accessing the Gemini CLI within Firebase Studio is straightforward, just press “Code view” in the top-right. From there, open up the terminal from the burger menu then select Terminal and New Terminal. Then in the terminal, type gemini and go through the setup, you can just press enter twice to get started. Out of the box, you’ll be able to get started with Gemini 2.5 Pro by just typing a query and pressing enter. There is also a non-interactive mode that’s useful for scripting and automation. To use it you use the –prompt or -p flags followed by your query wrapped in quotes, for example: gemini -p “What is the capital of France?” In this mode, Gemini CLI automatically closes after completing the request. During setup, there was the option to choose a theme. If you ever want to change it or look at other settings such as usage states, tool access, or checkpointing, you can edit them via .gemini/settings.json. You can also add API keys or choose different models in .env and you can using GEMINI.md to provide project-specific context, instructions, and coding styles in Gemini for a more tailored response. With Gemini CLI, you can have it explain code, refactor code, debug errors, and summarize information. It’s as simple as typing explain [file], refactor , debug “Error message”, or summarize “topic”. There are also built-in commands for managing the session such as /help for a command list, /chat to save and resume conversations, /tools to see available tools, and /restore to undo tool-made file edits. Firebase Studio, in true Google fashion, is a cloud-based IDE used in your web browser, making it excellent for weaker computers. To get started, you can head to the Firebase website. From there, tap Studio in the top-right.
    • I would prefer local ai over online ai on some tasks . They are good enough for tasks like artificial voice , image editing , text corrections , tagging etc . Local AI on Windows Photo editor is impressive for example . There are probably many other Ai that we could run on simple pc with GPUs .
    • oh look, we are under the control of the U.S again, is it not about time we as a country did this ourselves if they want it, not rely on greedy U.S. tech companies? We are capable of doing so as a country. I hate how the U.K have gone with no industry like we used to have and relying on other countries. Maybe we should follow Trump words, and make Britain great again and stop bending over to please Trump and other countries. Our government is Trumps puppet. I know we need to co-operate on some things, but come on.
  • Recent Achievements

    • Week One Done
      MIghty Haul earned a badge
      Week One Done
    • One Month Later
      MIghty Haul earned a badge
      One Month Later
    • Collaborator
      KD2004 earned a badge
      Collaborator
    • One Month Later
      ataho31016 earned a badge
      One Month Later
    • One Month Later
      Delahenty Machinery earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      592
    2. 2
      Michael Scrip
      200
    3. 3
      ATLien_0
      192
    4. 4
      +FloatingFatMan
      140
    5. 5
      Xenon
      127
  • Tell a friend

    Love Neowin? Tell a friend!